4.编写一个函数,由实参传来一个字符串,统计此字符串中字母、数字、空格和其他字符的个数,在主函数中输入字符串以及输出上述的结果。使用c代码,不要使用全局变量
时间: 2023-11-17 12:04:44 浏览: 59
以下是一个示例函数,可以实现计算字符串中字母、数字、空格和其他字符的个数:
```c
#include <stdio.h>
void count_chars(char *str, int *letters, int *digits, int *spaces, int *others) {
while (*str) {
if ((*str >= 'a' && *str <= 'z') || (*str >= 'A' && *str <= 'Z')) {
(*letters)++;
} else if (*str >= '0' && *str <= '9') {
(*digits)++;
} else if (*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` 函数接受一个字符串指针和四个整型指针作为参数。它使用一个 while 循环遍历字符串中的每个字符,并根据字符的类型增加相应的计数器。最后,它将计数器的值存储在各自的整型指针中。这个函数不使用全局变量,而是使用指针来传递计数器的值。在 `main` 函数中,我们使用 `fgets` 函数从标准输入中读取字符串,并调用 `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_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)