c语言,输入1个正整数n,在输入n个字符,分别统计其中英文字母、空格或回车、数字字符和其他字符的个数。(提示参照附录B) 【输入】 7 ab 88 * 【输出】2 2 2 1
时间: 2024-03-12 09:45:08 浏览: 32
好的,以下是 C 语言的代码实现:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
int n, cnt_alpha = 0, cnt_space = 0, cnt_digit = 0, cnt_other = 0;
char c;
scanf("%d", &n);
getchar(); // 读取换行符
for (int i = 0; i < n; i++) {
c = getchar();
if (isalpha(c)) {
cnt_alpha++;
} else if (isspace(c)) {
cnt_space++;
} else if (isdigit(c)) {
cnt_digit++;
} else {
cnt_other++;
}
}
printf("%d %d %d %d\n", cnt_alpha, cnt_space, cnt_digit, cnt_other);
return 0;
}
```
这段代码首先读入一个正整数 n,然后用一个 for 循环,读入 n 个字符,并统计其中的英文字母、空格或回车、数字字符和其他字符的个数。其中,isalpha 函数判断一个字符是否为英文字母,isspace 函数判断一个字符是否为空格或回车,isdigit 函数判断一个字符是否为数字字符。最后输出四种字符的个数。需要注意的是,读入完整个正整数 n 后,需要读取一次换行符,否则会影响后面的输入。