输入一行字符 分别统计出其中英文字母 空格 数字和其他字符个数 从标准输入流中读取
时间: 2023-11-07 16:59:31 浏览: 43
以下是 Python 代码实现:
```python
line = input("请输入一行字符:")
letter_count = 0
space_count = 0
digit_count = 0
other_count = 0
for c in line:
if c.isalpha():
letter_count += 1
elif c.isspace():
space_count += 1
elif c.isdigit():
digit_count += 1
else:
other_count += 1
print("字母个数:", letter_count)
print("空格个数:", space_count)
print("数字个数:", digit_count)
print("其他字符个数:", other_count)
```
输入一行字符后,程序会遍历每个字符并根据字符类型进行统计。最后输出各个类型的字符个数。
相关问题
用c语言写出输入一行字符,分别统计出其中英文字母、空格、数字和其他字符的个数。
可以使用C语言中的字符处理函数来判断每个字符的类型,并统计个数。以下是一种实现方式:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
int i, alpha=0, digit=0, space=0, other=0;
printf("请输入一行字符:");
fgets(str, 100, stdin);
for (i = 0; str[i] != '\0'; i++) {
if (isalpha(str[i])) {
alpha++;
} else if (isdigit(str[i])) {
digit++;
} else if (isspace(str[i])) {
space++;
} else {
other++;
}
}
printf("英文字母个数:%d\n", alpha);
printf("数字个数:%d\n", digit);
printf("空格个数:%d\n", space);
printf("其他字符个数:%d\n", other);
return 0;
}
```
其中,`fgets()`函数用于从标准输入流(即键盘)读取一行字符串,`isalpha()`、`isdigit()`和`isspace()`函数分别判断字符是否为字母、数字和空格,`alpha`、`digit`、`space`和`other`变量分别记录不同类型字符的个数。最后输出统计结果。
用c语言,输入一行字符,统计其中的英文字母、数字、空格和其他字符个数。
```c
#include <stdio.h>
int main() {
char str[100];
int i, letter, digit, space, other;
letter = digit = space = other = 0;
printf("请输入一行字符:\n");
fgets(str, 100, stdin);
for (i = 0; str[i] != '\0'; i++) {
if ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z')) {
letter++;
} else if (str[i] >= '0' && str[i] <= '9') {
digit++;
} else if (str[i] == ' ' || str[i] == '\t' || str[i] == '\n') {
space++;
} else {
other++;
}
}
printf("字母个数:%d\n", letter);
printf("数字个数:%d\n", digit);
printf("空格个数:%d\n", space);
printf("其他字符个数:%d\n", other);
return 0;
}
```
说明:
1. 定义字符数组 `str` 存储输入的一行字符。
2. 定义变量 `letter`、`digit`、`space`、`other` 分别表示字母、数字、空格和其他字符的个数,初始化为 0。
3. 使用 `fgets()` 函数从标准输入流中读取一行字符,存储到字符数组 `str` 中。
4. 使用 `for` 循环遍历字符数组 `str` 中的每个字符,判断其属于哪一类字符,分别累加对应的个数。
5. 输出统计结果。