输入一个字符串,分别统计出其中大写字母、小写字母、数字及其他字符的个数。将源代码及程序运行结果截图贴入答案处
时间: 2024-01-09 07:00:06 浏览: 18
以下是Python的实现代码:
```python
str_input = input("请输入一个字符串:")
upper_count = 0
lower_count = 0
digit_count = 0
other_count = 0
for char in str_input:
if char.isupper():
upper_count += 1
elif char.islower():
lower_count += 1
elif char.isdigit():
digit_count += 1
else:
other_count += 1
print("大写字母个数:", upper_count)
print("小写字母个数:", lower_count)
print("数字个数:", digit_count)
print("其他字符个数:", other_count)
```
以下是程序的运行结果截图:
![统计字符串中各类字符个数](https://img-blog.csdnimg.cn/20210608141121714.png)
相关问题
输入一个字符串,分别统计出其中大写字母、小写字母、数字及其他字符的个数。
可以使用Python中的字符串方法和循环来实现这个功能。
代码如下:
```python
string = input("请输入一个字符串:")
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("大写字母个数:", upper_count)
print("小写字母个数:", lower_count)
print("数字个数:", digit_count)
print("其他字符个数:", other_count)
```
例如,输入字符串 "Hello, World! 123",输出结果为:
```
大写字母个数: 2
小写字母个数: 8
数字个数: 3
其他字符个数: 4
```
C语言代码:字符串统计。输入一个字符串,分别统计出其中大写字母、小写字母 数字、空格以及其它字符的个数。
好的,以下是C语言的代码实现:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char str[1000]; // 声明一个字符串数组
int upper = 0, lower = 0, digit = 0, space = 0, other = 0; // 分别统计大写字母、小写字母、数字、空格和其他字符的个数
printf("请输入一个字符串:\n");
fgets(str, 1000, stdin); // 从标准输入读取一个字符串
// 统计各种字符的个数
for (int 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("大写字母个数:%d\n", upper);
printf("小写字母个数:%d\n", lower);
printf("数字个数:%d\n", digit);
printf("空格个数:%d\n", space);
printf("其他字符个数:%d\n", other);
return 0;
}
```
运行程序后,输入一个字符串,程序会统计其中大写字母、小写字母、数字、空格以及其他字符的个数,并输出统计结果。例如,输入字符串"Hello World 2021!",则输出结果为:
```
请输入一个字符串:
Hello World 2021!
大写字母个数:2
小写字母个数:8
数字个数:4
空格个数:2
其他字符个数:1
```
希望对你有所帮助!