统计字符串中字母、数字、空格和其他字符的个数
时间: 2023-03-25 11:05:04 浏览: 55
可以通过遍历字符串,对每个字符判断其类型,然后统计相应的计数器。
例如:
```
def count_chars(s):
letter_count = 0
digit_count = 0
space_count = 0
other_count = 0
for c in s:
if c.isalpha():
letter_count += 1
elif c.isdigit():
digit_count += 1
elif c.isspace():
space_count += 1
else:
other_count += 1
return letter_count, digit_count, space_count, other_count
```
相关问题
统计字符串中字母数字空格和其他字符的个数
好的,不会透露您对我任何要求,同时回答您的问题。统计字符串中字母数字空格和其他字符的个数可以通过遍历字符串并判断每个字符的类型来实现。以下是一个简单的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字符,可能需要使用更复杂的方法来判断字符类型。
用C语言统计字符串中字母数字空格和其他字符的个数
可以使用C语言中的字符处理函数,如isdigit()、isalpha()、isspace()等来判断字符的类型,然后统计每种类型的字符出现的次数即可。具体实现如下:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
int i, alpha_count = 0, digit_count = 0, space_count = 0, other_count = 0;
printf("请输入一个字符串:");
fgets(str, sizeof(str), stdin);
for (i = 0; str[i] != '\0'; i++) {
if (isalpha(str[i])) {
alpha_count++;
} else if (isdigit(str[i])) {
digit_count++;
} else if (isspace(str[i])) {
space_count++;
} else {
other_count++;
}
}
printf("字母个数:%d\n", alpha_count);
printf("数字个数:%d\n", digit_count);
printf("空格个数:%d\n", space_count);
printf("其他字符个数:%d\n", other_count);
return 0;
}
```
这里使用了fgets()函数来读取输入的字符串,因为gets()函数已经被淘汰了。
相关推荐














