c编写一个函数,统计字符串中字母、数字、空格和其他字符的个数,在主函数 中调用该函数完成统计、字符串的输入,以及结果输出。
时间: 2023-11-17 15:17:28 浏览: 41
可以使用以下C语言代码实现:
```c
#include <stdio.h>
#include <ctype.h>
void count(char str[], int *letter, int *digit, int *space, int *other) {
int i = 0;
while (str[i] != '\0') {
if (isalpha(str[i])) {
(*letter)++;
} else if (isdigit(str[i])) {
(*digit)++;
} else if (isspace(str[i])) {
(*space)++;
} else {
(*other)++;
}
i++;
}
}
int main() {
char str[100];
int letter = 0, digit = 0, space = 0, other = 0;
printf("请输入一个字符串:");
fgets(str, sizeof(str), stdin);
count(str, &letter, &digit, &space, &other);
printf("字母个数:%d\n", letter);
printf("数字个数:%d\n", digit);
printf("空格个数:%d\n", space);
printf("其他字符个数:%d\n", other);
return 0;
}
```
在这个程序中,`count`函数用来统计字符串中的各种字符个数,通过指针参数返回计数结果。主函数中使用`fgets`函数读取输入的字符串,然后调用`count`函数完成统计。最后输出各种字符的个数。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)