从键盘上输入一个字符串,统计集中的大写字母,小写字母,空格,数字字符以及其他字符个数,要求用指针对字符串进行访问
时间: 2025-06-09 13:02:49 浏览: 22
当你需要从键盘输入的字符串中统计大写字母、小写字母、空格、数字和其他字符的数量时,可以使用C语言中的数组和指针来实现这个功能。这里是一个简单的示例:
```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;
// 使用指针遍历字符串
char* ptr = str;
while (*ptr != '\0') { // 遍历直到字符串结束
if (isupper(*ptr)) { // 判断是否为大写字母
uppercase++;
} else if (islower(*ptr)) { // 判断是否为小写字母
lowercase++;
} else if (*ptr == ' ') { // 判断是否为空格
spaces++;
} else if (isdigit(*ptr)) { // 判断是否为数字
digits++;
} else { // 其他字符(非字母、空格或数字)
others++;
}
ptr++; // 指针向后移动一位
}
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); // 读取用户输入
count_chars(input); // 调用函数统计字符
return 0;
}
```
在这个程序中,`count_chars` 函数接收一个指向字符串的指针,通过遍历每个字符并利用 `ctype.h` 中的函数判断其类别,逐个累加计数。在 `main` 函数里,我们获取用户输入并通过 `fgets` 读入,并传递给 `count_chars` 进行统计。
阅读全文
相关推荐
















