c语言编程 编写一个函数,由实参传来一个字符串,统计此字符串中字母、数字、空格和其它字符的个数,在主函数中输入字符串以及输出上述结果。
时间: 2023-11-17 09:59:27 浏览: 186
以下是一个使用 C 语言编写的函数,用于统计字符串中字母、数字、空格和其他字符的个数:
```c
#include <stdio.h>
#include <ctype.h>
void count_chars(char *str, int *letters, int *digits, int *spaces, int *others) {
int i = 0;
char ch;
while ((ch = str[i++]) != '\0') {
if (isalpha(ch)) {
(*letters)++;
} else if (isdigit(ch)) {
(*digits)++;
} else if (isspace(ch)) {
(*spaces)++;
} else {
(*others)++;
}
}
}
int main() {
char str[100];
int letters = 0, digits = 0, spaces = 0, others = 0;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
count_chars(str, &letters, &digits, &spaces, &others);
printf("The input string contains:\n");
printf("%d letters\n", letters);
printf("%d digits\n", digits);
printf("%d spaces\n", spaces);
printf("%d other characters\n", others);
return 0;
}
```
在主函数中,我们首先定义了一个 char 类型的数组 str,用于存储输入的字符串。然后定义了四个 int 类型的变量 letters、digits、spaces 和 others,分别用于存储字母、数字、空格和其他字符的个数。
接下来我们使用 printf 函数输出提示信息,要求用户输入一个字符串。使用 fgets 函数从标准输入流中读取用户输入的字符串,并将其存储到 str 数组中。
然后我们调用 count_chars 函数,将 str 数组以及指向变量 letters、digits、spaces 和 others 的指针作为实参传递给函数。在函数内部,我们使用 while 循环遍历字符串中的每个字符,使用 isalpha、isdigit 和 isspace 函数判断该字符是字母、数字还是空格,并对应地更新变量 letters、digits 和 spaces 的值。如果一个字符既不是字母、数字,也不是空格,则认为它是其他字符,并更新变量 others 的值。
最后在主函数中,我们使用 printf 函数输出统计结果。
注意,在本例中使用了指向变量的指针,原因是函数调用需要修改这些变量的值。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![png](https://img-home.csdnimg.cn/images/20210720083516.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)