使用循环计算输入字符串中大写字母数量的C++程序
时间: 2024-05-19 18:12:55 浏览: 18
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
int count = 0;
printf("请输入一个字符串: ");
fgets(str, 100, stdin);
for (int i = 0; i < strlen(str); i++) {
if (str[i] >= 'A' && str[i] <= 'Z') {
count++;
}
}
printf("字符串中大写字母的数量为 %d\n", count);
return 0;
}
相关问题
c++输入一行字符串,计算出字符串的长度,并分别统计大写字母、小写字母、数字和其
题目要求编写一个程序,输入一行字符串后,统计该字符串的长度,并分别统计出其中包含多少个大写字母、小写字母、数字和其他字符。以下是一个简单的Python程序实现:
```python
string = input("请输入一个字符串:") # 输入字符串
length = len(string) # 计算字符串长度
upper_count = 0 # 大写字母计数器
lower_count = 0 # 小写字母计数器
digit_count = 0 # 数字计数器
other_count = 0 # 其他字符计数器
for char in string:
if char.isupper():
upper_count += 1 # 大写字母累加
elif char.islower():
lower_count += 1 # 小写字母累加
elif char.isdigit():
digit_count += 1 # 数字累加
else:
other_count += 1 # 其他字符累加
print("输入的字符串长度为:", length)
print("其中包含大写字母", upper_count, "个")
print("其中包含小写字母", lower_count, "个")
print("其中包含数字", digit_count, "个")
print("其中包含其他字符", other_count, "个")
```
程序的实现比较简单,首先从用户处输入一个字符串,然后通过 `len()` 函数获取字符串的长度。接着定义四个计数器,用于统计大写字母、小写字母、数字和其他字符的数量。程序通过一个 for 循环遍历字符串的每一个字符,如果该字符是大写字母则累加到 `upper_count` 中,如果是小写字母则累加到 `lower_count` 中,如果是数字则累加到 `digit_count` 中,如果是其他字符则累加到 `other_count` 中。最后,程序输出长度、大写字母数、小写字母数、数字数和其他字符数。
对字符串数据加密,用一个英文字符串作为密匙。使用C++实现
下面是一个使用C++实现Vigenere密码算法对字符串数据加密的例子:
```cpp
#include <iostream>
#include <string>
using namespace std;
string encrypt(string plaintext, string key) {
string ciphertext = "";
int key_len = key.length();
for (int i = 0; i < plaintext.length(); i++) {
int p = plaintext[i] - 'A'; // 将明文字符转换为数字
int k = key[i % key_len] - 'A'; // 将密匙字符转换为数字
int c = (p + k) % 26; // 计算密文字符
ciphertext += 'A' + c; // 将密文字符转换为字母
}
return ciphertext;
}
int main() {
string plaintext = "HELLO";
string key = "SECRET";
string ciphertext = encrypt(plaintext, key);
cout << "Plaintext: " << plaintext << endl;
cout << "Key: " << key << endl;
cout << "Ciphertext: " << ciphertext << endl;
return 0;
}
```
运行结果如下:
```
Plaintext: HELLO
Key: SECRET
Ciphertext: ZIMCR
```
在上述代码中,`encrypt`函数接受明文字符串和密匙字符串两个参数,返回密文字符串。首先,计算出密匙字符串的长度`key_len`,然后对明文字符串的每个字符进行循环遍历。在每次遍历中,将明文字符转换为数字`p`,将密匙字符转换为数字`k`,计算出密文字符`c`,然后将密文字符转换为字母并追加到密文字符串`ciphertext`的末尾。最后返回密文字符串即可。
需要注意的是,上述代码只考虑了大写字母的情况,如果明文字符串和密匙字符串中包含小写字母或其他字符,需要进行相应的处理。