如何用C语言编写一个程序来统计字符串中英文字母、空格、数字以及其它字符的具体数量?
时间: 2024-12-22 17:21:28 浏览: 47
在C语言中,你可以通过遍历字符串并利用ASCII码特性来统计每个类型的字符数。下面是一个简单的示例程序:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
int alpha_count = 0, space_count = 0, digit_count = 0, other_count = 0;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
// 去除fgets添加的换行符
str[strlen(str) - 1] = '\0';
for (int i = 0; str[i]; i++) { // 遍历字符串
if (isalpha(str[i])) { // 检查是否为字母
alpha_count++;
} else if (isspace(str[i])) { // 检查是否为空格
space_count++;
} else if (isdigit(str[i])) { // 检查是否为数字
digit_count++;
} else { // 其他字符
other_count++;
}
}
printf("\nCharacter count:\n");
printf("Alphabets: %d\n", alpha_count);
printf("Spaces: %d\n", space_count);
printf("Digits: %d\n", digit_count);
printf("Other characters: %d\n", other_count);
return 0;
}
```
这个程序首先获取用户输入的字符串,然后逐个检查每个字符,利用`isalpha()`、`isspace()`和`isdigit()`函数判断其类别,并累加相应的计数器。
阅读全文
相关推荐

















