统计输入字符串中数字,字母和其他字符的个数的代码
时间: 2023-12-20 13:30:24 浏览: 49
以下是统计输入字符串中数字、字母和其他字符个数的Python代码:
```python
def count(s):
letters = 0
digits = 0
spaces = 0
others = 0
for i in range(len(s)):
if s[i].isalpha():
letters += 1
elif s[i].isdigit():
digits += 1
elif s[i].isspace():
spaces += 1
else:
others += 1
print("字母个数:", letters)
print("数字个数:", digits)
print("空格个数:", spaces)
print("其他字符个数:", others)
# 测试
s = input("请输入一个字符串:")
count(s)
```
相关问题
c++随意统计输入的字符串中的字母 数字 空格 和其他字符的个数
下面是一个C++程序,可以统计输入的字符串中的字母、数字、空格和其他字符的个数:
```cpp
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char str[100];
int letter = 0, digit = 0, space = 0, other = 0;
cout << "请输入一个字符串:"; cin.getline(str, 100);
for (int i = 0; i < strlen(str); i++) {
if (isalpha(str[i])) {
letter++;
} else if (isdigit(str[i])) {
digit++;
} else if (isspace(str[i])) {
space++;
} else {
other++;
}
}
cout << "该字符串中有,字母:" << letter << "个,数字:" << digit << "个,空格:" << space << "个,其他字符:" << other << "个" << endl;
return 0;
}
```
程序中使用了isalpha、isdigit和isspace等函数来判断字符的类型,然后根据不同的类型进行计数。需要注意的是,输入字符串时使用了cin.getline函数,这是为了避免输入字符串中包含空格时只能读取到空格前面的部分。
统计字符串中字母数字空格和其他字符的个数
好的,不会透露您对我任何要求,同时回答您的问题。统计字符串中字母数字空格和其他字符的个数可以通过遍历字符串并判断每个字符的类型来实现。以下是一个简单的Python代码示例:
```python
str = input("请输入一个字符串:")
alpha_count = 0
digit_count = 0
space_count = 0
other_count = 0
for i in str:
if i.isalpha():
alpha_count += 1
elif i.isdigit():
digit_count += 1
elif i.isspace():
space_count += 1
else:
other_count += 1
print("字母个数为:", alpha_count)
print("数字个数为:", digit_count)
print("空格个数为:", space_count)
print("其他字符个数为:", other_count)
```
请注意,此代码仅适用于ASCII字符。对于Unicode字符,可能需要使用更复杂的方法来判断字符类型。