用C语言编写程序解决 输入一行字符,分别统计出其中英文字母、空格、数字和其他的个数
时间: 2024-06-13 22:05:20 浏览: 21
这是两种用C语言编写的程序,用于统计输入的一行字符中英文字母、空格、数字和其他字符的个数。第一种方法是常规计算,通过循环遍历每个字符并判断其类型,最后输出各个类型字符的个数。第二种方法是通过调用普通函数实现,同样是通过循环遍历每个字符并判断其类型,最后输出各个类型字符的个数。这两种方法都可以实现相同的功能,只是实现方式略有不同。
相关问题
用c语言的循环语句输入一行字符分别统计出其中英文字母空格数字和其他字符的个数
使用C语言的循环语句可以输入一行字符并统计其中英文字母、空格、数字和其他字符的个数。下面是一个示例代码:
```c
#include <stdio.h>
int main() {
char c;
int ch, s, d, o;
ch = 0;
s = 0;
d = 0;
o = 0;
while ((c = getchar()) != '\n') {
if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z')
ch++;
else if (c == ' ')
s++;
else if (c >= '0' && c <= '9')
d++;
else
o++;
}
printf("char=%d space=%d digit=%d others=%d\n", ch, s, d, o);
return 0;
}
```
该代码使用了一个while循环来读取输入的字符,然后使用if语句来判断字符的类型并相应地增加计数器的值。最后,使用printf函数输出统计结果。
C语言编写程序:输入一行字符,分别统计出其中英文字母、空格、数字和其他字符的个数
以下是统计字符个数的 C 语言代码:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char line[100];
int i, alphabet = 0, digit = 0, space = 0, other = 0;
printf("请输入一行字符: ");
fgets(line, sizeof(line), stdin);
for (i = 0; line[i] != '\0'; ++i) {
if (isalpha(line[i])) {
++alphabet;
}
else if (isdigit(line[i])) {
++digit;
}
else if (isspace(line[i])) {
++space;
}
else {
++other;
}
}
printf("英文字母个数: %d\n", alphabet);
printf("数字个数: %d\n", digit);
printf("空格个数: %d\n", space);
printf("其他字符个数: %d\n", other);
return 0;
}
```
这段代码使用了 for 循环遍历输入的字符数组,对每个字符进行判断,若是英文字母则 alphabet++,若是数字则 digit++,若是空格则 space++,其他字符则 other++。最终输出各个字符的个数。注意,需要包含头文件 ctype.h 才能使用 isalpha 和 isdigit 函数。