用C语言编写程序:输入一行文字,找出其中大写字母、小写字母、空格、数字以及其他字符的个数,要求用指针完成。
时间: 2025-01-01 09:37:45 浏览: 29
在C语言中,你可以使用指针和字符数组来实现这个功能。这里是一个简单的示例程序:
#include <stdio.h>
#include <ctype.h> // 包含处理字符种类的库函数
void count_chars(char *str) {
int uppercase = 0;
int lowercase = 0;
int spaces = 0;
int digits = 0;
int others = 0;
while (*str != '\0') { // 遍历字符串直到遇到结束符
if (isupper(*str)) { // 检查是否为大写字母
uppercase++;
} else if (islower(*str)) { // 检查是否为小写字母
lowercase++;
} else if (*str == ' ') { // 检查是否为空格
spaces++;
} else if (isdigit(*str)) { // 检查是否为数字
digits++;
} else { // 其他字符(非字母、空格或数字)
others++;
}
str++; // 移动到下一个字符
}
printf("大写字母: %d\n", uppercase);
printf("小写字母: %d\n", lowercase);
printf("空格: %d\n", spaces);
printf("数字: %d\n", digits);
printf("其他字符: %d\n", others);
}
int main() {
char input[100];
printf("请输入一行文字: ");
fgets(input, sizeof(input), stdin); // 读取一行用户输入并忽略换行符
input[strlen(input) - 1] = '\0'; // 将fgets读取的换行符替换为结束符
count_chars(input);
return 0;
}
在这个程序中,count_chars
函数通过遍历输入的字符串,并使用 isupper
、islower
、isspace
和 isdigit
函数检查每个字符,统计不同类型的字符数量。
相关推荐

















