用C语言编写一个函数,由实参传来一个字符串,统计此字符串中字母、数字、空格和其他字符的个数,在主函数中输入字符串并在主函数中输出统计结果。 输入 任意一个字符串(长度小于80)。 输出 统计其中的英文字母、数字、空格以及其他字符的个数。
时间: 2023-06-12 17:03:29 浏览: 65
以下是C语言代码实现:
```c
#include <stdio.h>
#include <ctype.h>
void countChars(const char *str, int *letters, int *digits, int *spaces, int *others) {
while (*str) {
if (isalpha(*str)) {
(*letters)++;
} else if (isdigit(*str)) {
(*digits)++;
} else if (isspace(*str)) {
(*spaces)++;
} else {
(*others)++;
}
str++;
}
}
int main() {
char str[80];
int letters = 0, digits = 0, spaces = 0, others = 0;
printf("请输入一个字符串:");
gets(str); // 读取输入字符串
countChars(str, &letters, &digits, &spaces, &others);
printf("字母个数:%d\n", letters);
printf("数字个数:%d\n", digits);
printf("空格个数:%d\n", spaces);
printf("其他字符个数:%d\n", others);
return 0;
}
```
在该程序中,`countChars`函数接收一个指向字符串的指针和四个整型指针,分别用于记录字母、数字、空格和其他字符的个数。在函数中,使用`isalpha`、`isdigit`和`isspace`等标准库函数判断字符属于哪一类,然后逐个统计各类字符的个数。
在`main`函数中,先读取用户输入的字符串,然后调用`countChars`函数统计各类字符的个数,最后输出统计结果。
需要注意的是,该程序中使用了`gets`函数读取输入字符串,但是该函数存在安全漏洞,不建议在实际生产代码中使用。建议使用更加安全的`fgets`函数代替。