C语编写一个函数,由实参传入一串字符,统计这串字符中字母、数字、空格、和其他 字符的个数,在主函数中输入字符串以及输出上述结果。
时间: 2023-09-27 10:05:58 浏览: 77
### 回答1:
可以使用以下代码实现:
```c
#include <stdio.h>
void count(char *str, int *alpha, int *num, int *space, int *other) {
while (*str) {
if ((*str >= 'a' && *str <= 'z') || (*str >= 'A' && *str <= 'Z')) {
(*alpha)++;
} else if (*str >= '0' && *str <= '9') {
(*num)++;
} else if (*str == ' ') {
(*space)++;
} else {
(*other)++;
}
str++;
}
}
int main() {
char str[100];
int alpha = 0, num = 0, space = 0, other = 0;
printf("请输入一个字符串:");
fgets(str, 100, stdin);
count(str, &alpha, &num, &space, &other);
printf("字母个数:%d\n", alpha);
printf("数字个数:%d\n", num);
printf("空格个数:%d\n", space);
printf("其他字符个数:%d\n", other);
return 0;
}
```
在主函数中,用户通过输入一个字符串来调用 `count` 函数,该函数统计该字符串中字母、数字、空格和其他字符的个数,最后将结果通过指针返回给主函数,主函数再输出结果。
### 回答2:
可以使用C语言编写一个函数来统计给定字符串中的字母、数字、空格和其他字符的个数。主要的步骤如下:
```c
#include <stdio.h>
void countCharacters(char* str, int* letters, int* numbers, int* spaces, int* others){
int i = 0;
while(str[i] != '\0'){
if((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z')){
// 如果是字母
(*letters)++;
}
else if(str[i] >= '0' && str[i] <= '9'){
// 如果是数字
(*numbers)++;
}
else if(str[i] == ' '){
// 如果是空格
(*spaces)++;
}
else{
// 其他字符
(*others)++;
}
i++;
}
}
int main(){
char str[100];
printf("请输入一个字符串:");
fgets(str, 100, stdin);
int letters = 0, numbers = 0, spaces = 0, others = 0;
countCharacters(str, &letters, &numbers, &spaces, &others);
printf("字母个数:%d\n", letters);
printf("数字个数:%d\n", numbers);
printf("空格个数:%d\n", spaces);
printf("其他字符个数:%d\n", others);
return 0;
}
```
在上面的代码中,我们首先定义了一个`countCharacters`的函数。该函数接收一个字符指针作为参数,以及四个整型指针,用于存储统计结果。然后,我们使用一个循环遍历字符串中的每个字符,判断其是否为字母、数字、空格或其他字符,并根据判断结果增加相应的计数器。最后,在主函数中通过调用`countCharacters`函数来统计给定字符串,并输出结果。
请注意,上述代码中使用了`fgets`函数来获取输入字符串,以避免可能的缓冲区溢出问题。此外,我们还将统计结果作为指针传递给`countCharacters`函数,以便在函数内部可以直接修改相应变量的值。
### 回答3:
一个实现上述功能的C语言函数可以像这样编写:
```c
#include <stdio.h>
void countChars(char* str, int* count_letters, int* count_digits, int* count_spaces, int* count_others) {
// 遍历字符串中的每个字符
char ch;
while (*str) {
ch = *str++;
// 判断字符是字母、数字、空格还是其他字符
if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) {
(*count_letters)++;
}
else if (ch >= '0' && ch <= '9') {
(*count_digits)++;
}
else if (ch == ' ') {
(*count_spaces)++;
}
else {
(*count_others)++;
}
}
}
int main() {
char str[100];
printf("请输入一串字符:");
fgets(str, 100, stdin);
int count_letters = 0, count_digits = 0, count_spaces = 0, count_others = 0;
countChars(str, &count_letters, &count_digits, &count_spaces, &count_others);
printf("字母个数: %d\n", count_letters);
printf("数字个数: %d\n", count_digits);
printf("空格个数: %d\n", count_spaces);
printf("其他字符个数: %d\n", count_others);
return 0;
}
```
这个函数名为`countChars`,它接受一个字符指针`str`作为实参,以及四个整数指针`count_letters`、`count_digits`、`count_spaces`和`count_others`,用于存储结果。函数中使用一个`while`循环遍历字符串中的每个字符,并根据字符类型进行计数。最后,主函数中调用`countChars`函数,输入字符串,并输出统计结果。