用c语言编写一个函数,由实参传来一个字符串,统计此字符串中字母、数字、空格和其它字符的个数,在主函数中输入字符串以及输出上述结果
时间: 2025-01-27 09:11:02 浏览: 41
以下是一个用C语言编写的函数,用于统计字符串中字母、数字、空格和其它字符的个数:
```c
#include <stdio.h>
#include <ctype.h>
void count_characters(const char *str, int *letters, int *digits, int *spaces, int *others) {
while (*str) {
if (isalpha(*str)) {
(*letters)++;
} else if (isdigit(*str)) {
(*digits)++;
} else if (isspace(*str)) {
(*spaces)++;
} else {
(*others)++;
}
str++;
}
}
int main() {
char str[1000];
int letters = 0, digits = 0, spaces = 0, others = 0;
printf("请输入一个字符串:\n");
fgets(str, sizeof(str), stdin);
count_characters(str, &letters, &digits, &spaces, &others);
printf("字母个数:%d\n", letters);
printf("数字个数:%d\n", digits);
printf("空格个数:%d\n", spaces);
printf("其它字符个数:%d\n", others);
return 0;
}
```
这个程序包含以下几个部分:
1. `count_characters` 函数:
- 接受一个字符串和四个整型指针作为参数。
- 遍历字符串中的每个字符。
- 使用 `ctype.h` 库中的函数来判断字符类型,并相应地增加计数器。
2. `main` 函数:
- 定义一个字符数组来存储输入的字符串。
- 定义四个整型变量来存储统计结果。
- 提示用户输入字符串,并使用 `fgets` 函数读取输入。
- 调用 `count_characters` 函数进行统计。
- 输出统计结果。
3. 包含必要的头文件:
- `stdio.h` 用于输入输出函数。
- `ctype.h` 用于字符判断函数。
使用这个程序,用户可以输入一个字符串,程序将统计并显示其中字母、数字、空格和其它字符的个数。
阅读全文
相关推荐
















