C语言输入一个以回车符结束的字符串(不超过255个字符),分别统计其中的大写字母、小写字母、数字字符和其他字符的个数。
时间: 2025-01-18 22:06:17 浏览: 55
以下是一个用C语言编写的程序,它可以输入一个以回车符结束的字符串(不超过255个字符),并分别统计其中的大写字母、小写字母、数字字符和其他字符的个数:
```c
#include <stdio.h>
#include <ctype.h>
#define MAX_LENGTH 255
int main() {
char str[MAX_LENGTH + 1];
int uppercase = 0, lowercase = 0, digits = 0, others = 0;
int i = 0;
printf("请输入一个字符串(不超过255个字符):\n");
while (i < MAX_LENGTH && (str[i] = getchar()) != '\n') {
i++;
}
str[i] = '\0'; // 添加字符串结束符
for (i = 0; str[i] != '\0'; i++) {
if (isupper(str[i])) {
uppercase++;
} else if (islower(str[i])) {
lowercase++;
} else if (isdigit(str[i])) {
digits++;
} else {
others++;
}
}
printf("统计结果:\n");
printf("大写字母:%d\n", uppercase);
printf("小写字母:%d\n", lowercase);
printf("数字字符:%d\n", digits);
printf("其他字符:%d\n", others);
return 0;
}
```
这个程序的工作原理如下:
1. 定义了一个字符数组 `str` 来存储输入的字符串,最大长度为255个字符加一个结束符。
2. 使用 `getchar()` 函数逐个读取字符,直到遇到回车符 '\n' 或达到最大长度。
3. 使用 `isupper()`, `islower()`, 和 `isdigit()` 函数来判断每个字符的类别。
4. 遍历字符串数组,统计大写字母、小写字母、数字字符和其他字符的数量。
5. 最后,输出统计结果。
这个程序可以有效地统计输入字符串中各种类型字符的数量,同时处理了输入长度限制和字符串结束符的问题。
阅读全文
相关推荐



















