编写函数fun(s),fun可以返回字符串s中的小写字母,大写字母和数字字符的个数分别是多少
时间: 2023-10-31 12:04:43 浏览: 43
以下是Python语言的实现:
```python
def fun(s):
lowercase_count = 0
uppercase_count = 0
digit_count = 0
for char in s:
if char.islower():
lowercase_count += 1
elif char.isupper():
uppercase_count += 1
elif char.isdigit():
digit_count += 1
return lowercase_count, uppercase_count, digit_count
```
函数`fun`接收一个字符串`s`作为参数,然后遍历字符串中的每个字符,用`islower()`方法判断是否为小写字母,用`isupper()`方法判断是否为大写字母,用`isdigit()`方法判断是否为数字字符,然后根据不同的情况分别增加计数器的值。
最后,函数返回三个计数器的值,即小写字母、大写字母和数字字符的个数。
相关问题
用python编写函数fun(s),fun可以返回字符串s中的大写字母的个数,小写字母的个数和数字的个数。(要求有调用过程)
可以使用isupper()、islower()、isdigit()等函数来判断字符的类型,然后统计个数即可。以下是一个示例代码:
```python
def fun(s):
upper_count = 0
lower_count = 0
digit_count = 0
for c in s:
if c.isupper():
upper_count += 1
elif c.islower():
lower_count += 1
elif c.isdigit():
digit_count += 1
return upper_count, lower_count, digit_count
# 调用过程
s = "Hello World! 123"
result = fun(s)
print(f"大写字母个数:{result[0]},小写字母个数:{result[1]},数字个数:{result[2]}")
```
输出结果为:
```
大写字母个数:2,小写字母个数:8,数字个数:3
```
以void fun设计C++:键盘输入一个字符串,统计其中的大写字母、小写字母、数字字母、其他字符的个数。
下面是一个以 `void fun` 设计的 C++ 函数,用于统计字符串中的大写字母、小写字母、数字和其他字符的个数:
```c++
#include <iostream>
#include <cctype>
using namespace std;
void fun(string s){
int upper = 0, lower = 0, digit = 0, other = 0;
for(char ch : s){
if(isupper(ch)){
upper++;
}
else if(islower(ch)){
lower++;
}
else if(isdigit(ch)){
digit++;
}
else{
other++;
}
}
cout << "大写字母个数:" << upper << endl;
cout << "小写字母个数:" << lower << endl;
cout << "数字个数:" << digit << endl;
cout << "其他字符个数:" << other << endl;
}
int main(){
string s;
cout << "请输入字符串:";
getline(cin, s); // 使用 getline 函数读取一行字符串
fun(s);
return 0;
}
```
在上面的代码中,我们使用了 `isupper`、`islower` 和 `isdigit` 函数来判断字符是否为大写字母、小写字母和数字,使用了一个计数器来统计各种类型字符出现的次数,并最终输出结果。