C语言统计字符中小写字母、大写字母、数字、其他字符的个数;
时间: 2023-08-31 20:53:04 浏览: 113
要统计字符串中小写字母、大写字母、数字和其他字符的个数,可以使用C语言的字符处理函数和条件语句来实现。下面是一个示例代码:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
printf("输入一个字符串:");
fgets(str, sizeof(str), stdin);
// 删除换行符
str[strcspn(str, "\n")] = '\0';
int lowercaseCount = 0;
int uppercaseCount = 0;
int digitCount = 0;
int otherCount = 0;
for (int i = 0; str[i] != '\0'; i++) {
if (islower(str[i])) {
lowercaseCount++;
} else if (isupper(str[i])) {
uppercaseCount++;
} else if (isdigit(str[i])) {
digitCount++;
} else {
otherCount++;
}
}
printf("小写字母个数:%d\n", lowercaseCount);
printf("大写字母个数:%d\n", uppercaseCount);
printf("数字个数:%d\n", digitCount);
printf("其他字符个数:%d\n", otherCount);
return 0;
}
```
在这个示例中,我们首先声明一个字符数组`str`来存储用户输入的字符串。然后使用`fgets`函数从标准输入读取字符串,并将其存储在`str`中。接着使用`strcspn`函数找到字符串中的换行符,并将其替换为字符串结束符`\0`,以去除输入时可能包含的换行符。
然后我们声明四个变量`lowercaseCount`、`uppercaseCount`、`digitCount`和`otherCount`,分别用于记录小写字母、大写字母、数字和其他字符的个数。
接下来使用一个循环遍历字符串中的每个字符,使用`islower`、`isupper`和`isdigit`函数判断字符的类型,并根据判断结果递增相应的计数器。
最后输出统计结果。
请注意,这个示例代码中假设输入的字符串不包含空格和特殊字符。如果需要考虑空格和特殊字符的情况,可以在循环中添加相应的判断条件。
阅读全文
相关推荐
















