函数、简单循环 【问题描述]从键盘输入字符串,统计其中大写字母的、小写字母、数字以及其他字符的个数。 设置 (字符串) [输入形式]含有大写字母、数字等其他字符的字符串 [输出形式]统计的个数
时间: 2024-10-27 12:14:49 浏览: 49
在Python中,你可以创建一个函数来完成这个任务,利用内置的`isupper()`, `islower()`, 和 `isdigit()` 函数判断每个字符的类型。这里是一个简单的解决方案:
```python
def count_characters(s):
uppercase_count = sum(c.isupper() for c in s)
lowercase_count = sum(c.islower() for c in s)
digit_count = sum(c.isdigit() for c in s)
other_count = len(s) - (uppercase_count + lowercase_count + digit_count)
return uppercase_count, lowercase_count, digit_count, other_count
# 用户输入
input_string = input("请输入字符串:")
uppercase, lowercase, digits, others = count_characters(input_string)
print(f"大写字母有 {uppercase} 个,小写字母有 {lowercase} 个,数字有 {digits} 个,其他字符有 {others} 个。")
相关问题
输入一个长度小于100的字符串统计其中大写字母小写字母数字以及其他字符的个数
以下是Python的解法:
```python
s = input("请输入一个字符串:")
uppercase = lowercase = digit = other = 0
for c in s:
if c.isupper():
uppercase += 1
elif c.islower():
lowercase += 1
elif c.isdigit():
digit += 1
else:
other += 1
print(f"大写字母有{uppercase}个,小写字母有{lowercase}个,数字有{digit}个,其他字符有{other}个")
```
以上程序中,通过`input()`函数获取用户输入的字符串,然后循环遍历每个字符,通过字符串方法`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`,这些函数可以判断字符是否为大写字母、小写字母、数字或空格字符。
阅读全文
相关推荐















