编写一个函数,统计字符串中字母、数字、空格 和其它字符个数并输出。
时间: 2023-11-17 17:01:20 浏览: 33
好的,这是一个关于字符串操作的问题。以下是解决方案:
```python
def count_chars(str):
letter, digit, space, other = 0, 0, 0, 0
for i in str:
if i.isalpha():
letter += 1
elif i.isdigit():
digit += 1
elif i.isspace():
space += 1
else:
other += 1
print("字母个数:", letter)
print("数字个数:", digit)
print("空格个数:", space)
print("其他字符个数:", other)
# 测试
str = "Hello World! 123"
count_chars(str)
```
输出结果:
```
字母个数: 10
数字个数: 3
空格个数: 2
其他字符个数: 1
```
希望能够解决您的问题!
相关问题
用C语言编写一个函数,统计字符串中字母数字空格和其他字符的个数,在主函数中调用该函数完成统计字符串输入以及结果输出
以下是用C语言编写的函数,可以实现统计字符串中字母、数字、空格和其他字符的个数:
```c
#include <stdio.h>
#include <ctype.h>
void count_chars(char *str, int *alpha, int *num, int *space, int *other) {
char c;
while (*str != '\0') {
c = *str++;
if (isalpha(c)) {
(*alpha)++;
} else if (isdigit(c)) {
(*num)++;
} else if (isspace(c)) {
(*space)++;
} else {
(*other)++;
}
}
}
int main() {
char str[100];
int alpha = 0, num = 0, space = 0, other = 0;
printf("请输入字符串:");
fgets(str, sizeof(str), stdin);
count_chars(str, &alpha, &num, &space, &other);
printf("字母个数:%d\n数字个数:%d\n空格个数:%d\n其他字符个数:%d\n", alpha, num, space, other);
return 0;
}
```
在主函数中,首先输入字符串,然后调用 `count_chars` 函数,将字符串和各个类型字符的计数器的指针作为参数传递给它。函数内部使用循环遍历字符串中的每个字符,判断它是字母、数字、空格还是其他字符,并累加相应的计数器。最后,在主函数中输出各个类型字符的个数。
C语言中编一函数,统计一个字符串中字母数字空格和其他字符的个数
好的,这个问题可以通过编写一个函数来实现。下面是一个简单的 C 语言函数示例:
```c
#include <stdio.h>
#include <ctype.h>
void count_chars(const char *str, int *alpha, int *num, int *space, int *other) {
while (*str) {
if (isalpha(*str))
(*alpha)++;
else if (isdigit(*str))
(*num)++;
else if (*str == ' ')
(*space)++;
else
(*other)++;
str++;
}
}
int main() {
int alpha = 0, num = 0, space = 0, other = 0;
char str[] = "Hello, 123 world!";
count_chars(str, &alpha, &num, &space, &other);
printf("Alpha: %d\n", alpha);
printf("Num: %d\n", num);
printf("Space: %d\n", space);
printf("Other: %d\n", other);
return 0;
}
```
这个函数接收一个字符串和四个指针变量作为参数,分别统计字母、数字、空格和其他字符的数量,并将结果存储在指针变量中。在主函数中,我们可以传入一个测试字符串,并打印出结果。
注意:本人是 AI 语言模型,对于代码的语法分析能力很强,但对于代码的执行能力很弱。本回答提供的代码仅供参考,实际运行效果可能存在问题。