输入一行字符回车结束编程统计其中大写字母小写字母数字字符空格和其他字符的个数c语言
时间: 2023-11-07 22:26:12 浏览: 136
#include <stdio.h>
int main() {
char ch;
int upper = 0, lower = 0, digit = 0, space = 0, other = 0;
printf("请输入一行字符:\n");
while ((ch = getchar()) != '\n') {
if (ch >= 'A' && ch <= 'Z') {
upper++;
} else if (ch >= 'a' && ch <= 'z') {
lower++;
} else if (ch >= '0' && ch <= '9') {
digit++;
} else if (ch == ' ') {
space++;
} else {
other++;
}
}
printf("大写字母个数:%d\n", upper);
printf("小写字母个数:%d\n", lower);
printf("数字个数:%d\n", digit);
printf("空格个数:%d\n", space);
printf("其他字符个数:%d\n", other);
return 0;
}
相关问题
输入一行字符,统计其中大写字母、小写字母、数字、空格和其他字符的个数
要统计一行字符中大写字母、小写字母、数字、空格和其他字符的个数,你可以使用C语言中的`ctype.h`库来检查每个字符的类型。以下是一个简单的程序示例:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char input[100]; // 假设最多输入100个字符
fgets(input, sizeof(input), stdin); // 从标准输入读取一行字符
int uppercase = 0;
int lowercase = 0;
int digits = 0;
int spaces = 0;
int others = 0;
for (int i = 0; input[i] != '\0'; i++) { // 遍历输入字符串
if (isupper(input[i])) { // 检查是否为大写字母
uppercase++;
} else if (islower(input[i])) { // 检查是否为小写字母
lowercase++;
} else if (isdigit(input[i])) { // 检查是否为数字
digits++;
} else if (input[i] == ' ') { // 检查是否为空格
spaces++;
} else { // 其他字符(包括标点符号等)
others++;
}
}
printf("大写字母: %d\n", uppercase);
printf("小写字母: %d\n", lowercase);
printf("数字: %d\n", digits);
printf("空格: %d\n", spaces);
printf("其他字符: %d\n", others);
return 0;
}
```
在这个程序中,我们使用了`isupper()`、`islower()`、`isdigit()`函数分别检测字符是否为大写、小写和数字,而对空格和其他字符进行直接计数。运行这个程序后,它会显示每个类别字符的数量。
c语言统计字符串大写字母小写字母数字,输入并统计字符串中大写字母、小写字母、数字字符、空格字符和其他字符的个数...
以下是一个简单的 C 代码示例,可以统计字符串中大写字母、小写字母、数字字符、空格字符和其他字符的个数:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
int i, upper_count = 0, lower_count = 0, digit_count = 0, space_count = 0, other_count = 0;
printf("请输入一个字符串:");
fgets(str, sizeof(str), stdin);
for (i = 0; str[i] != '\0'; i++) {
if (isupper(str[i])) {
upper_count++;
} else if (islower(str[i])) {
lower_count++;
} else if (isdigit(str[i])) {
digit_count++;
} else if (isspace(str[i])) {
space_count++;
} else {
other_count++;
}
}
printf("大写字母个数:%d\n", upper_count);
printf("小写字母个数:%d\n", lower_count);
printf("数字个数:%d\n", digit_count);
printf("空格个数:%d\n", space_count);
printf("其他字符个数:%d\n", other_count);
return 0;
}
```
代码解释:
1. 定义一个字符数组 `str` 用于存储输入的字符串。
2. 定义五个整型变量 `upper_count`、`lower_count`、`digit_count`、`space_count` 和 `other_count`,分别用于统计大写字母、小写字母、数字字符、空格字符和其他字符的个数,初始化为 0。
3. 使用 `fgets` 函数从标准输入读取字符串,存储到数组 `str` 中。
4. 使用 `for` 循环遍历字符串中的每个字符,如果字符是大写字母,将 `upper_count` 加 1;如果字符是小写字母,将 `lower_count` 加 1;如果字符是数字,将 `digit_count` 加 1;如果字符是空格,将 `space_count` 加 1;否则将 `other_count` 加 1。
5. 使用 `printf` 函数输出统计结果。
注意事项:
1. 该代码示例假设字符串中只包含 ASCII 字符。如果包含其他字符集,需要根据具体情况进行修改。
2. 该代码示例中使用了 C 标准库中的函数 `isupper`、`islower`、`isdigit` 和 `isspace`,这些函数可以判断字符是否为大写字母、小写字母、数字或空格字符。
阅读全文
相关推荐














