使用指针编程:输入一行文字,统计其中大写字母、小写字母、数字、空格、其他字符的个数,并输出显示。
时间: 2024-12-10 16:41:47 浏览: 69
在指针编程中,你可以使用C语言的字符处理函数以及指针来完成这个任务。首先,定义一个字符指针遍历输入的文字字符串,然后根据ASCII码值来判断每个字符属于哪种类型:
#include <stdio.h>
#include <ctype.h>
void count_chars(char* str) {
int uppercase = 0;
int lowercase = 0;
int digits = 0;
int spaces = 0;
int others = 0;
while (*str != '\0') { // 遍历直到遇到字符串结束符
if (isupper(*str)) { // 检查是否为大写字母
uppercase++;
} else if (islower(*str)) { // 检查是否为小写字母
lowercase++;
} else if (isdigit(*str)) { // 检查是否为数字
digits++;
} else if (*str == ' ') { // 检查是否为空格
spaces++;
} else { // 其他字符
others++;
}
str++; // 移动指针到下一个字符
}
printf("大写字母: %d\n", uppercase);
printf("小写字母: %d\n", lowercase);
printf("数字: %d\n", digits);
printf("空格: %d\n", spaces);
printf("其他字符: %d\n", others);
}
int main() {
char input[100];
printf("请输入一行文字: ");
fgets(input, sizeof(input), stdin); // 读取用户输入
// 去除fgets末尾的换行符
input[strlen(input)-1] = '\0';
count_chars(input);
return 0;
}
当你运行程序并输入一行文字后,它会统计出每种字符类型的个数。
相关推荐


















