用C语言编写函数,要求由实参传来一个字符串,统计此字符串中字母,数字,空格和其他字符的个数,在主函数main()中输入统计字符结果。
时间: 2024-06-09 16:09:45 浏览: 23
下面是一个用C语言编写的函数,可以实现统计字符串中字母,数字,空格和其他字符的个数的功能:
```c
#include <stdio.h>
#include <ctype.h>
void count_chars(char *str, int *letters, int *digits, int *spaces, int *others) {
while (*str != '\0') {
if (isalpha(*str)) {
(*letters)++;
} else if (isdigit(*str)) {
(*digits)++;
} else if (isspace(*str)) {
(*spaces)++;
} else {
(*others)++;
}
str++;
}
}
int main() {
char str[100];
int letters = 0, digits = 0, spaces = 0, others = 0;
printf("请输入一个字符串:");
fgets(str, 100, stdin);
count_chars(str, &letters, &digits, &spaces, &others);
printf("字母个数:%d\n", letters);
printf("数字个数:%d\n", digits);
printf("空格个数:%d\n", spaces);
printf("其他字符个数:%d\n", others);
return 0;
}
```
在上面的代码中,`count_chars` 函数接受一个字符串指针和四个整数指针作为参数,分别用于存储字母、数字、空格和其他字符的个数。在函数中,我们使用 `isalpha`、`isdigit` 和 `isspace` 函数来判断字符属于哪一类,然后将对应类型的计数器加一。最后,我们在主函数 `main` 中调用 `count_chars` 函数,并输出统计结果。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)