c语言统计字符串数字, 字母,空格和其他字符个数
时间: 2025-02-17 20:22:45 浏览: 32
在C语言中,你可以通过遍历字符串并利用`ctype.h`库提供的函数来统计字符串中的各种字符类型。下面是一个简单的例子,它会计算字符串中的数字、字母、空格和其他字符的数量:
```c
#include <stdio.h>
#include <ctype.h>
#include <string.h>
void count_chars(char *str) {
int num_digits = 0;
int num_letters = 0;
int num_spaces = 0;
int num_other = 0;
for (int i = 0; str[i] != '\0'; i++) {
if (isdigit(str[i])) { // 检查是否是数字
num_digits++;
} else if (isalpha(str[i])) { // 检查是否是字母
num_letters++;
} else if (isspace(str[i])) { // 检查是否是空格
num_spaces++;
} else { // 其他字符(包括特殊字符)
num_other++;
}
}
printf("Number of digits: %d\n", num_digits);
printf("Number of letters: %d\n", num_letters);
printf("Number of spaces: %d\n", num_spaces);
printf("Number of other characters: %d\n", num_other);
}
int main() {
char input[] = "Hello, World! 123";
count_chars(input);
return 0;
}
```
当你运行这个程序,它会打印出给定字符串中各类字符的具体数量。
阅读全文
相关推荐

















