分类统计字符的个数,输入一行字符串,统计其中的大写字母,小写字母,空格,数字字符与其他字符
时间: 2023-08-02 19:09:27 浏览: 85
可以用Python编写以下程序实现:
```python
s = input() # 输入一行字符串
uppercase = 0 # 统计大写字母的个数
lowercase = 0 # 统计小写字母的个数
space = 0 # 统计空格的个数
digit = 0 # 统计数字字符的个数
other = 0 # 统计其他字符的个数
# 遍历字符串中的每个字符
for c in s:
if c.isupper(): # 如果是大写字母
uppercase += 1
elif c.islower(): # 如果是小写字母
lowercase += 1
elif c.isspace(): # 如果是空格
space += 1
elif c.isdigit(): # 如果是数字字符
digit += 1
else: # 否则是其他字符
other += 1
# 输出统计结果
print("大写字母个数:", uppercase)
print("小写字母个数:", lowercase)
print("空格个数:", space)
print("数字字符个数:", digit)
print("其他字符个数:", other)
```
输入一个字符串后,程序会依次遍历字符串中的每个字符,根据字符的类型来统计各种字符的个数,并最终输出统计结果。
相关问题
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()` 函数,分别用来判断一个字符是否为大写字母、小写字母、空格和数字。
分类统计字符的个数,输入一行字符串,统计其中的大写字母,小写字母,空格,数字字符与其他字符个数用C语言
```c
#include <stdio.h>
#include <ctype.h> // 包含字符处理函数
int main() {
char str[100];
int i, upper = 0, lower = 0, space = 0, digit = 0, other = 0;
printf("请输入一行字符串:\n");
gets(str);
for (i = 0; str[i] != '\0'; i++) {
if (isupper(str[i])) // 判断是否为大写字母
upper++;
else if (islower(str[i])) // 判断是否为小写字母
lower++;
else if (isspace(str[i])) // 判断是否为空格
space++;
else if (isdigit(str[i])) // 判断是否为数字字符
digit++;
else
other++; // 其他字符
}
printf("大写字母个数:%d\n", upper);
printf("小写字母个数:%d\n", lower);
printf("空格个数:%d\n", space);
printf("数字字符个数:%d\n", digit);
printf("其他字符个数:%d\n", other);
return 0;
}
```