C语言编写一个函数,由实参传来一个字符串,统计此字符串中字母、数字、空格和其他字符的个数,在主函数中输入字符串以及输出上述的结果。
时间: 2025-07-06 19:52:21 浏览: 9
### C语言实现统计字符串中字母、数字、空格和其他字符数量
#### 定义辅助函数
为了完成这个任务,可以创建一个名为 `count_chars` 的函数,此函数接收一个指向字符串的指针作为参数并计算其中不同类型的字符数目。
```c
#include <stdio.h>
#include <ctype.h>
void count_chars(const char *str, int *letters, int *digits, int *spaces, int *others) {
while (*str != '\0') { // 遍历整个字符串直到遇到终止符'\0'
if (isalpha((unsigned char)*str)) (*letters)++;
else if (isdigit((unsigned char)*str)) (*digits)++;
else if (isspace((unsigned char)*str)) (*spaces)++;
else (*others)++;
++str;
}
}
```
上述代码利用了 `<ctype.h>` 头文件提供的宏来判断字符类别[^3]。对于每一个字符:
- 如果它是英文字母,则增加 `*letters` 计数器;
- 若为阿拉伯数字,则使 `*digits` 自增;
- 当前字符为空白(包括空格、制表符等),则累加到 `*spaces` 上;
- 否则认为是非字母非数字也非空白的其他字符,并更新 `*others` 变量。
#### 编写主程序
接下来,在 `main()` 函数内调用上面定义好的 `count_chars` 方法来进行实际的数据处理工作,并打印最终的结果给用户查看。
```c
int main(void){
const char input[] = "Hello world! 123";
int letters = 0, digits = 0, spaces = 0, others = 0;
printf("Input string is \"%s\"\n", input);
count_chars(input, &letters, &digits, &spaces, &others);
printf("Letters: %d\nDigits: %d\nSpaces: %d\nOthers: %d\n",
letters, digits, spaces, others);
return 0;
}
```
这段简单的测试案例会输出如下信息:
```
Input string is "Hello world! 123"
Letters: 10
Digits: 3
Spaces: 1
Others: 1
```
通过这种方式实现了对任意给定字符串内的各类字符计数的功能。
阅读全文
相关推荐

















