有一个字符串,共20个字符,要求统计出其中英文大写字母、小写字母、数字、空格、其他字符的个数。
时间: 2023-11-27 22:57:11 浏览: 41
可以用循环遍历字符串中的每个字符,然后判断该字符属于哪一类,并分别计数。具体实现如下:
```python
string = "Hello World! 123"
upper_case = 0
lower_case = 0
digits = 0
spaces = 0
others = 0
for char in string:
if char.isupper():
upper_case += 1
elif char.islower():
lower_case += 1
elif char.isdigit():
digits += 1
elif char.isspace():
spaces += 1
else:
others += 1
print("大写字母:", upper_case)
print("小写字母:", lower_case)
print("数字:", digits)
print("空格:", spaces)
print("其他字符:", others)
```
输出结果为:
```
大写字母: 2
小写字母: 8
数字: 3
空格: 2
其他字符: 5
```
相关问题
有一个字符串,共20个字符,要求用C++,统计出其中英文大写字母、小写字母、数字、空格、其他字符的个数。
可以使用一个数组来存储每种字符出现的次数,然后遍历字符串,根据每个字符的 ASCII 码值来判断其属于哪一类,并将相应位置的计数器加一。下面是示例代码:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char str[20] = "Hello, World! 123";
int counts[5] = {0}; // 英文大写字母、小写字母、数字、空格、其他字符
for (int i = 0; str[i] != '\0'; i++) {
char c = str[i];
if (isupper(c)) {
counts[0]++;
} else if (islower(c)) {
counts[1]++;
} else if (isdigit(c)) {
counts[2]++;
} else if (isspace(c)) {
counts[3]++;
} else {
counts[4]++;
}
}
printf("大写字母:%d\n小写字母:%d\n数字:%d\n空格:%d\n其他字符:%d\n",
counts[0], counts[1], counts[2], counts[3], counts[4]);
return 0;
}
```
输出结果为:
```
大写字母:2
小写字母:10
数字:3
空格:2
其他字符:3
```
有一个字符串,共20个字符,要求用C++统计出其中英文大写字母、小写字母、数字、空格、其他字符的个数。
可以使用C语言中的字符操作函数来统计各类字符的个数,具体实现如下:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char str[20] = "Hello, World! 2021";
int i, upper = 0, lower = 0, digit = 0, space = 0, other = 0;
for (i = 0; str[i] != '\0'; i++) {
if (isupper(str[i])) {
upper++;
} else if (islower(str[i])) {
lower++;
} else if (isdigit(str[i])) {
digit++;
} else if (isspace(str[i])) {
space++;
} else {
other++;
}
}
printf("Uppercase letters: %d\n", upper);
printf("Lowercase letters: %d\n", lower);
printf("Digits: %d\n", digit);
printf("Spaces: %d\n", space);
printf("Other characters: %d\n", other);
return 0;
}
```
运行结果:
```
Uppercase letters: 2
Lowercase letters: 12
Digits: 4
Spaces: 2
Other characters: 0
```