如何在C语言中统计字符串中英文字母、数字、空格和其他字符的数量?
时间: 2025-02-22 16:32:29 浏览: 84
在C语言中,我们可以遍历字符串并使用不同的条件判断来统计各种类型的字符。下面是一个简单的示例,展示了如何计算英文字符(只包括大写字母和小写字母)、数字、空格以及其他特殊字符的数量:
```c
#include <stdio.h>
#include <ctype.h>
void count_chars(char* str) {
int alpha_count = 0, digit_count = 0, space_count = 0, other_count = 0;
for (int i = 0; str[i] != '\0'; i++) {
// 统计英文字母
if (isalpha(str[i])) {
if (islower(str[i])) // 小写字母
alpha_count++;
else if (isupper(str[i])) // 大写字母
alpha_count++;
}
// 统计数字
else if (isdigit(str[i]))
digit_count++;
// 统计空格
else if (str[i] == ' ')
space_count++;
// 其他字符(如标点符号)
else
other_count++;
}
printf("Number of letters: %d\n", alpha_count);
printf("Number of digits: %d\n", digit_count);
printf("Number of spaces: %d\n", space_count);
printf("Number of other characters: %d\n", other_count);
}
int main() {
char str[100];
printf("Enter a string: ");
fgets(str, sizeof(str), stdin); // 注意fgets会保留换行符
count_chars(str);
return 0;
}
```
在这个例子中,我们使用了`ctype.h`库里的`isalpha`、`isdigit`以及`isspace`函数来检查每个字符是否属于特定的类别。
阅读全文
相关推荐


















