写一段程序:输入一串字符,统计英文字母、空格、数字、和其他字符个数
时间: 2024-03-22 16:17:36 浏览: 14
以下是Python的程序实现:
```
string = input("请输入一串字符:")
# 初始化计数器
letter_count = 0
digit_count = 0
space_count = 0
other_count = 0
# 遍历字符串中的每个字符,判断它属于哪一类
for char in string:
if char.isalpha():
letter_count += 1
elif char.isdigit():
digit_count += 1
elif char.isspace():
space_count += 1
else:
other_count += 1
# 输出统计结果
print("英文字母数量:", letter_count)
print("数字数量:", digit_count)
print("空格数量:", space_count)
print("其他字符数量:", other_count)
```
程序先输入一串字符,然后利用 `for` 循环遍历每个字符,通过 `isalpha()`、`isdigit()`、`isspace()` 函数判断这个字符属于哪一类,并对应的计数器加一。最后输出各类字符的数量。
相关问题
C语言写程序:输入一行字符,分别统计其中的英文字母、空格、数字和其他字符的个数
这是一段C语言程序,它的功能是输入一行字符,然后统计其中的英文字母、空格、数字和其他字符的个数。程序使用了gets函数来获取用户输入的字符串,然后使用for循环遍历字符串中的每个字符,根据字符的类型进行统计。最后输出统计结果。
以下是回答:
这段C语言程序的功能是输入一行字符,然后统计其中的英文字母、空格、数字和其他字符的个数。程序使用了gets函数来获取用户输入的字符串,然后使用for循环遍历字符串中的每个字符,根据字符的类型进行统计。最后输出统计结果。
具体来说,程序使用了四个变量来分别统计英文字母、数字、空格和其他字符的个数。在for循环中,使用了if语句来判断当前字符的类型,并根据类型对相应的变量进行加一操作。最后,使用printf函数输出统计结果。
用c语言写输入一行字符分别统计英文字母空格数字和其他字符
好的,这个问题是关于C语言的,我可以回答。下面是C语言代码:
```
#include <stdio.h>
int main() {
char str[100];
int letters = 0, spaces = 0, digits = 0, others = 0;
printf("请输入一个字符串:");
fgets(str, 100, stdin);
for (int i = 0; str[i] != '\0'; i++) {
if ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z')) {
letters++;
} else if (str[i] == ' ') {
spaces++;
} else if (str[i] >= '0' && str[i] <= '9') {
digits++;
} else {
others++;
}
}
printf("字母个数:%d\n", letters);
printf("空格个数:%d\n", spaces);
printf("数字个数:%d\n", digits);
printf("其他字符个数:%d\n", others);
return 0;
}
```
这段代码通过遍历输入的字符数组,统计英文字母、空格、数字和其他字符的出现次数,并输出结果。希望能够帮到你!