输入一段英文,统计其中英文大写字母、小写字母、数字和其它字符的个数。c++
时间: 2023-04-23 22:04:34 浏览: 56
以下是C++代码:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
int upper = , lower = , digit = , other = ;
cout << "请输入一段英文:";
getline(cin, str);
for (int i = ; i < str.length(); i++)
{
if (isupper(str[i]))
upper++;
else if (islower(str[i]))
lower++;
else if (isdigit(str[i]))
digit++;
else
other++;
}
cout << "大写字母个数:" << upper << endl;
cout << "小写字母个数:" << lower << endl;
cout << "数字个数:" << digit << endl;
cout << "其它字符个数:" << other << endl;
return ;
}
相关问题
c++编写程序.能够输入一行不含空格的字符串.统计其中的大写字母小写字母和数字的个数
好的,以下是C++编写的程序,可以实现输入一行不含空格的字符串,统计其中的大写字母、小写字母和数字的个数:
```c++
#include <iostream>
using namespace std;
int main() {
string str;
int upper = 0, lower = 0, digit = 0;
cout << "请输入一行不含空格的字符串:" << endl;
getline(cin, str); // 输入一行字符串
for (char c : str) {
if (c >= 'A' && c <= 'Z') {
upper++;
} else if (c >= 'a' && c <= 'z') {
lower++;
} else if (c >= '0' && c <= '9') {
digit++;
}
}
cout << "大写字母个数:" << upper << endl;
cout << "小写字母个数:" << lower << endl;
cout << "数字个数:" << digit << endl;
return 0;
}
```
程序思路如下:
1. 使用 `string` 类型的变量 `str` 存储输入的字符串;
2. 定义三个变量 `upper`、`lower` 和 `digit` 分别代表大写字母、小写字母和数字的个数,初始化为 0;
3. 使用 `getline` 函数从标准输入流中读取一行字符串赋值给 `str`;
4. 使用 `for` 循环遍历字符串中的每个字符,通过字符的 ASCII 码值判断它是大写字母、小写字母还是数字,并分别对应将 `upper`、`lower` 和 `digit` 变量的值加 1;
5. 输出统计结果。
运行程序,输入一行不含空格的字符串,即可得到大写字母、小写字母和数字的个数。
c++输入一字符串,统计其中大写字母、小写字母、空格、数字及其他字符的个数
下面是一个简单的C++代码示例,可以实现统计字符串中各种字符的个数:
```c++
#include <iostream>
#include <ctype.h>
using namespace std;
int main()
{
string str;
int uppercase = 0, lowercase = 0, space = 0, digit = 0, other = 0;
getline(cin, str); // 读入一行字符串
for (int i = 0; i < str.length(); i++) {
char c = str[i];
if (isupper(c)) {
uppercase++;
} else if (islower(c)) {
lowercase++;
} else if (isspace(c)) {
space++;
} else if (isdigit(c)) {
digit++;
} else {
other++;
}
}
cout << "大写字母个数:" << uppercase << endl;
cout << "小写字母个数:" << lowercase << endl;
cout << "空格个数:" << space << endl;
cout << "数字个数:" << digit << endl;
cout << "其他字符个数:" << other << endl;
return 0;
}
```
注意,这里使用了 `<ctype.h>` 库中的 `isupper()`、`islower()`、`isspace()` 和 `isdigit()` 函数,分别用来判断一个字符是否为大写字母、小写字母、空格和数字。