用c语言统计一个字符串中字母、数字、空格及其它字符的数量
时间: 2024-12-06 13:26:08 浏览: 130
在C语言中,你可以通过遍历字符串并判断每个字符所属的类别来统计字母、数字、空格和其他字符的数量。这里是一个简单的示例:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
int count_letters = 0;
int count_digits = 0;
int count_spaces = 0;
int count_other = 0;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin); // 防止超长输入
str[strcspn(str, "\n")] = '\0'; // 去除换行符
for (int i = 0; str[i] != '\0'; i++) {
if (isalpha(str[i])) { // 判断是否为字母
count_letters++;
} else if (isdigit(str[i])) { // 判断是否为数字
count_digits++;
} else if (isspace(str[i])) { // 判断是否为空格
count_spaces++;
} else { // 其他字符
count_other++;
}
}
printf("Number of letters: %d\n", count_letters);
printf("Number of digits: %d\n", count_digits);
printf("Number of spaces: %d\n", count_spaces);
printf("Number of other characters: %d\n", count_other);
return 0;
}
```
在这个程序中,`isalpha()` 函数用于检查字符是否为字母,`isdigit()` 检查是否为数字,`isspace()` 则判断是否为空格。非这三者的情况就被视为其他字符。
阅读全文
相关推荐
















