编写程序,要求输入字符串,计算字符串中大写字母和小写字母的个数并输出,计算过程用函数实现
时间: 2024-05-11 14:14:42 浏览: 9
```python
def count_upper_lower(s):
count_upper = 0
count_lower = 0
for c in s:
if c.isupper():
count_upper += 1
elif c.islower():
count_lower += 1
return count_upper, count_lower
s = input("请输入字符串:")
count_upper, count_lower = count_upper_lower(s)
print("大写字母个数:", count_upper)
print("小写字母个数:", count_lower)
```
相关问题
编写程序,要求输入字符串,计算字符串中大写字母和小写字母的个数并输出,计算过程用函数实现。
好的,这个问题很简单,我来帮你实现一个计算字符串中大写字母和小写字母的个数的函数:
```python
def count_upper_lower(string):
upper_count = 0
lower_count = 0
for char in string:
if char.isupper():
upper_count += 1
elif char.islower():
lower_count += 1
return upper_count, lower_count
```
你可以通过调用这个函数来计算字符串中大写字母和小写字母的个数,比如这样:
```python
string = input("请输入字符串:")
upper_count, lower_count = count_upper_lower(string)
print("大写字母个数:", upper_count)
print("小写字母个数:", lower_count)
```
希望能够帮到你。
用c语言实现输入一组字符串,计算字符串中数字、大写字母和小写字母的个数
以下是用C语言实现输入一组字符串,计算字符串中数字、大写字母和小写字母的个数的代码:
```c
#include <stdio.h>
#include <ctype.h> // 用于判断字符类型的库函数
int main() {
char str[100]; // 声明一个字符串数组
int num_count = 0, upper_count = 0, lower_count = 0;
// 初始化数字、大写字母和小写字母的个数为0
printf("请输入字符串:");
fgets(str, sizeof(str), stdin); // 从标准输入读取字符串
for (int i = 0; str[i] != '\0'; i++) {
if (isdigit(str[i])) { // 判断是否为数字
num_count++;
} else if (isupper(str[i])) { // 判断是否为大写字母
upper_count++;
} else if (islower(str[i])) { // 判断是否为小写字母
lower_count++;
}
}
printf("数字个数:%d\n", num_count);
printf("大写字母个数:%d\n", upper_count);
printf("小写字母个数:%d\n", lower_count);
return 0;
}
```
代码解析:
1. 首先声明一个大小为100的字符串数组 `str`,同时初始化数字、大写字母和小写字母的个数为0。
2. 使用 `fgets()` 函数从标准输入(即键盘)读取一行字符串,存储在 `str` 数组中。`fgets()` 函数的第一个参数是要读取数据的数组名称,第二个参数是数组的大小,第三个参数是文件指针,表示要读取的数据来源。因为我们要从键盘输入,所以使用标准输入流 `stdin`。
3. 使用 `for` 循环遍历字符串数组 `str` 中的每个字符,判断每个字符是否为数字、大写字母或小写字母,如果是则将相应计数器加1。
4. 最后使用 `printf()` 函数输出统计结果。
注意:
1. 在使用 `fgets()` 函数时,要注意输入的最大字符数不能超过指定的数组大小减1,因为字符串末尾需要有一个空字符 `\0`。
2. 在判断字符类型时,可以使用 `ctype.h` 头文件中提供的库函数,如 `isdigit()`、`isupper()` 和 `islower()` 等。