编写一个程序由实参传来一个字符串统计字符串中数字,字母,空格和其他字符的个数
时间: 2024-04-27 10:02:47 浏览: 14
以下是Python程序实现:
```python
def count_chars(s):
digits = letters = spaces = others = 0
for char in s:
if char.isdigit():
digits += 1
elif char.isalpha():
letters += 1
elif char.isspace():
spaces += 1
else:
others += 1
return digits, letters, spaces, others
s = input("请输入一个字符串:")
digits, letters, spaces, others = count_chars(s)
print("数字的个数为:", digits)
print("字母的个数为:", letters)
print("空格的个数为:", spaces)
print("其他字符的个数为:", others)
```
首先定义了一个函数`count_chars`,接收一个字符串`s`作为参数,并返回数字、字母、空格、其他字符的个数。
然后在函数内部定义四个变量`digits`、`letters`、`spaces`、`others`,分别表示数字、字母、空格、其他字符的个数,初始值均为0。
接着使用for循环遍历字符串`s`中的每一个字符,判断其属于哪一类字符,并将对应的计数器加1。
最后返回四个计数器的值。
在主程序中,首先接收用户输入的字符串,并调用`count_chars`函数统计各种字符的个数。
最后输出结果。