统计各类字符个数pta
时间: 2023-11-15 14:26:17 浏览: 46
好的,这是一个常见的字符串统计问题。你可以使用一个长度为 256 的整数数组来记录每个字符出现的次数,然后遍历字符串并更新数组中对应字符的计数器即可。以下是实现该算法的 C++ 代码示例:
```c++
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char str[1000];
int count[256] = {0};
// 读入字符串
cin.getline(str, 1000);
// 统计字符个数
int len = strlen(str);
for (int i = 0; i < len; i++) {
count[str[i]]++;
}
// 输出结果
for (int i = 0; i < 256; i++) {
if (count[i] > 0) {
printf("%c:%d\n", i, count[i]);
}
}
return 0;
}
```
这段代码可以统计输入字符串中每个字符出现的次数,并输出结果。注意,该算法假定输入的字符串只包含 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;
}
```