写函数,从键盘输入字符串,统计字符串中有几个字母,几个数字,几个空格,几个其他字符,并返回结果
时间: 2024-01-13 15:03:08 浏览: 19
可以使用 Python 的内置函数 `isalpha()`, `isdigit()`, 和 `isspace()` 来判断字符类型。下面是一个实现该功能的函数:
```python
def count_chars(s):
num_alpha = 0
num_digit = 0
num_space = 0
num_other = 0
for c in s:
if c.isalpha():
num_alpha += 1
elif c.isdigit():
num_digit += 1
elif c.isspace():
num_space += 1
else:
num_other += 1
return (num_alpha, num_digit, num_space, num_other)
```
这个函数接受一个字符串参数 `s`,然后遍历字符串中的每个字符,统计字母、数字、空格和其他字符的个数,并将结果作为元组返回。例如,对于字符串 `"Hello world! 123"`,函数的返回值将是 `(10, 3, 2, 1)`。
相关问题
pyhthon 写函数,统计字符串中有几个字母,几个数字,几个空格,几个其他字符,并返回结果;
可以使用 Python 的内置函数 `isalpha()`、`isdigit()`、`isspace()` 来判断一个字符是否为字母、数字、空格字符,然后遍历字符串中的每个字符,统计它们的个数,最后返回结果。以下是实现该功能的 Python 代码:
```python
def count_chars(string):
num_letters = 0
num_digits = 0
num_spaces = 0
num_others = 0
for char in string:
if char.isalpha():
num_letters += 1
elif char.isdigit():
num_digits += 1
elif char.isspace():
num_spaces += 1
else:
num_others += 1
return num_letters, num_digits, num_spaces, num_others
```
使用该函数,将一个字符串作为参数传递给它,即可统计该字符串中的字母、数字、空格、其他字符的数量。函数返回一个包含四个元素的元组,分别表示字母、数字、空格、其他字符的数量。以下是使用示例:
```python
string = "Hello, World! 123"
num_letters, num_digits, num_spaces, num_others = count_chars(string)
print("字母数量:", num_letters)
print("数字数量:", num_digits)
print("空格数量:", num_spaces)
print("其他字符数量:", num_others)
```
输出结果为:
```
字母数量: 10
数字数量: 3
空格数量: 3
其他字符数量: 2
```
求输入一个字符串,字符串里面有几个空格,用函数实现 c语言
可以使用以下代码实现:
```c
#include <stdio.h>
#include <string.h>
int count_spaces(char *str) {
int count = 0;
int len = strlen(str);
for (int i = 0; i < len; i++) {
if (str[i] == ' ') {
count++;
}
}
return count;
}
int main() {
char str[100];
printf("请输入一个字符串:");
fgets(str, 100, stdin); // 从标准输入读取字符串
int spaces = count_spaces(str);
printf("字符串中有 %d 个空格\n", spaces);
return 0;
}
```
首先定义一个函数 `count_spaces`,它接受一个字符串参数 `str`,并返回该字符串中空格的数量。
在函数中,我们先定义一个计数器 `count`,初始值为0,然后遍历字符串中的每个字符,如果当前字符是空格,则将计数器加1。
最后在 `main` 函数中,从标准输入读取一个字符串,调用 `count_spaces` 函数统计空格数量,并输出结果。