编写一个函数,由实参传来一个字符串,统计此字符串中字母、数字、空格和其它字符的个数,在主函数中输入字符串以及输入上述的结果。 用c语言编写
时间: 2025-01-03 20:44:14 浏览: 42
在 C 语言中,你可以创建一个函数来完成这个任务。这里是一个简单的函数示例,它接收一个字符串作为输入,然后分别计算字母、数字、空格和其他字符的数量:
```c
#include <stdio.h>
#include <ctype.h> // 包含用于处理字符类型的库
// 定义一个函数来统计字符类型
void count_chars(char* str) {
int alpha_count = 0; // 字母计数
int digit_count = 0; // 数字计数
int space_count = 0; // 空格计数
int other_count = 0; // 其他字符计数
while (*str != '\0') { // 遍历字符串直到结束
if (isalpha(*str)) { // 检查是否为字母
alpha_count++;
} else if (isdigit(*str)) { // 检查是否为数字
digit_count++;
} else if (*str == ' ') { // 检查是否为空格
space_count++;
} else { // 其他字符
other_count++;
}
str++; // 移动指针到下一个字符
}
printf("字母数量: %d\n", alpha_count);
printf("数字数量: %d\n", digit_count);
printf("空格数量: %d\n", space_count);
printf("其他字符数量: %d\n", other_count);
}
int main() {
char input[100];
printf("请输入一个字符串: ");
fgets(input, sizeof(input), stdin); // 从用户输入读取字符串,忽略换行符
input[strcspn(input, "\n")] = '\0'; // 清除fgets读取的换行符
count_chars(input);
return 0;
}
```
在这个程序中,`count_chars` 函数遍历输入的字符串并使用 `isalpha`, `isdigit`, 和 `isspace` 函数判断每个字符的类型。`main` 函数则获取用户的输入并调用该函数。
阅读全文
相关推荐















