输入一字符串,将字符串中的大写字母和小写字母分别转换成对应的小写字母和大写字母。并统计字符串中数字字符的个数
时间: 2023-11-16 17:57:13 浏览: 22
```
s = input("请输入一个字符串:")
count = 0 # 统计数字字符的个数
new_s = "" # 存储转换后的字符串
for c in s:
if c.isdigit(): # 如果是数字字符
count += 1
elif c.islower(): # 如果是小写字母
new_s += c.upper() # 转换为对应的大写字母
elif c.isupper(): # 如果是大写字母
new_s += c.lower() # 转换为对应的小写字母
else:
new_s += c # 其他字符不变
print("转换后的字符串为:", new_s)
print("数字字符的个数为:", count)
```
测试:
```
请输入一个字符串:AbC123dEf
转换后的字符串为:aBc123DeF
数字字符的个数为:3
```
相关问题
C语言输入一字符串,分别统计字符串中大写字母和小写字母的个数
以下是使用 C 语言编写的程序,统计字符串中大写字母和小写字母的个数:
```c
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main() {
char str[100];
int length;
int uppercase = 0;
int lowercase = 0;
printf("请输入字符串:");
scanf("%s", str);
length = strlen(str);
// 统计大写字母和小写字母的个数
for (int i = 0; i < length; i++) {
if (isupper(str[i])) {
uppercase++;
} else if (islower(str[i])) {
lowercase++;
}
}
printf("大写字母的个数为:%d\n", uppercase);
printf("小写字母的个数为:%d\n", lowercase);
return 0;
}
```
程序首先要求用户输入字符串,然后使用 `strlen` 函数获取字符串的长度。接下来,使用 `for` 循环遍历字符串的每个字符,如果字符为大写字母,则将 `uppercase` 的值加 1;如果字符为小写字母,则将 `lowercase` 的值加 1。最后,输出大写字母和小写字母的个数。在这个程序中,我们使用了 `ctype.h` 中的函数 `isupper` 和 `islower` 来判断字符是否为大写字母或小写字母。
c++输入一字符串,统计其中大写字母、小写字母、空格、数字及其他字符的个数
下面是一个简单的C++代码示例,可以实现统计字符串中各种字符的个数:
```c++
#include <iostream>
#include <ctype.h>
using namespace std;
int main()
{
string str;
int uppercase = 0, lowercase = 0, space = 0, digit = 0, other = 0;
getline(cin, str); // 读入一行字符串
for (int i = 0; i < str.length(); i++) {
char c = str[i];
if (isupper(c)) {
uppercase++;
} else if (islower(c)) {
lowercase++;
} else if (isspace(c)) {
space++;
} else if (isdigit(c)) {
digit++;
} else {
other++;
}
}
cout << "大写字母个数:" << uppercase << endl;
cout << "小写字母个数:" << lowercase << endl;
cout << "空格个数:" << space << endl;
cout << "数字个数:" << digit << endl;
cout << "其他字符个数:" << other << endl;
return 0;
}
```
注意,这里使用了 `<ctype.h>` 库中的 `isupper()`、`islower()`、`isspace()` 和 `isdigit()` 函数,分别用来判断一个字符是否为大写字母、小写字母、空格和数字。