编写一个函数,由实参传来一个字符串,统计此字符串中字母、数字、空格和其他字符的个数,在主函数中输入字符串以及输出上述的结果。解题思路
时间: 2023-11-17 18:03:49 浏览: 51
可以利用字符的 ASCII 码来判断一个字符的类型,具体实现如下:
```c
#include <stdio.h>
void count_chars(char *str, int *letters, int *digits, int *spaces, int *others) {
char c;
int i = 0;
while ((c = str[i++]) != '\0') {
if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') {
(*letters)++;
} else if (c >= '0' && c <= '9') {
(*digits)++;
} else if (c == ' ') {
(*spaces)++;
} else {
(*others)++;
}
}
}
int main() {
char str[100];
int letters = 0, digits = 0, spaces = 0, others = 0;
printf("请输入一个字符串:");
gets(str);
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` 函数统计了一个字符串中字母、数字、空格和其他字符的个数,并将结果保存在传入参数的指针中。在主函数中,首先输入一个字符串,然后调用 `count_chars` 函数并输出结果。注意,由于 C 语言中没有字符串类型,因此我们使用字符数组来存储字符串,并通过 `gets` 函数来输入字符串。同时,由于需要修改 `letters`、`digits`、`spaces` 和 `others` 变量的值,因此我们需要通过它们的指针来传递参数。