统计各类字符个数4-2
时间: 2024-05-06 13:15:55 浏览: 7
这道题目需要统计一段字符串中各类字符的个数。我们可以使用一个数组来记录每一类字符的出现次数,具体过程如下:
1. 初始化一个长度为 256 的整型数组 count,用于记录每一个 ASCII 码对应字符的出现次数。
2. 遍历字符串中的每一个字符,对于每一个字符,将 count 数组中对应的 ASCII 码的值加 1。
3. 遍历 count 数组,输出每一类字符出现的个数。
下面是具体的代码实现:
```python
def count_chars(s):
count = [0] * 256 # 初始化 count 数组
for c in s:
count[ord(c)] += 1 # 统计每一类字符的个数
for i in range(256):
if count[i] > 0:
print(chr(i), count[i]) # 输出每一类字符出现的个数
```
这里用到了 Python 中的 ord() 函数,它可以将一个字符转换为它的 ASCII 码。chr() 函数则相反,可以将一个 ASCII 码转换为它对应的字符。
相关问题
分类统计各类字符个数
以下是分类统计各类字符个数的示例代码:
```c
#include <stdio.h>
#include <ctype.h>
void StringCount(char *s) {
int upper = 0, lower = 0, space = 0, digit = 0, other = 0;
while (*s != '\0') {
if (isupper(*s)) {
upper++;
} else if (islower(*s)) {
lower++;
} else if (*s == ' ') {
space++;
} else if (isdigit(*s)) {
digit++;
} else {
other++;
}
s++;
}
printf("%d %d %d %d %d", upper, lower, space, digit, other);
}
```
该函数接收一个字符串指针作为参数,然后遍历整个字符串,统计其中大写字母、小写字母、空格、数字以及其它字符的个数,并按照 大写字母个数 小写字母个数 空格个数 数字个数 其它字符个数 的格式输出。
c语言统计各类字符个数
以下是C语言统计各类字符个数的代码实现:
```c
#include <stdio.h>
#include <ctype.h>
int main()
{
char ch;
int letter = 0, digit = 0, space = 0, other = 0;
while ((ch = getchar()) != EOF)
{
if (isalpha(ch)) // 判断是否为字母
{
letter++;
}
else if (isdigit(ch)) // 判断是否为数字
{
digit++;
}
else if (isspace(ch)) // 判断是否为空格
{
space++;
}
else // 其他字符
{
other++;
}
}
printf("字母个数:%d\n", letter);
printf("数字个数:%d\n", digit);
printf("空格个数:%d\n", space);
printf("其他字符个数:%d\n", other);
return 0;
}
```