统计字符串出现的次数c语言
时间: 2023-11-11 15:02:33 浏览: 30
可以使用一个哈希表来记录每个字符出现的次数,具体实现如下:
```c
#include <stdio.h>
#include <string.h>
#define MAXN 100000
int cnt[256]; // 哈希表,记录每个字符出现的次数
int main() {
char s[MAXN];
scanf("%s", s);
int len = strlen(s);
for (int i = 0; i < len; ++i)
++cnt[s[i]]; // 更新哈希表
for (int i = 0; i < 256; ++i)
if (cnt[i]) // 如果字符出现过
printf("%c: %d\n", i, cnt[i]); // 输出字符和出现次数
return 0;
}
```
这里使用了一个长度为 256 的数组作为哈希表,因为 ASCII 码一共只有 256 个字符,每个字符对应一个数组下标。我们可以通过字符的 ASCII 码值来计算出它在哈希表中的下标,从而实现字符和出现次数的统计。
相关问题
C语言统计字符串出现次数
以下是两种C语言统计字符串中各个字符出现次数的方法:
1.使用数组统计字符出现次数
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
int i, num[256] = {0};
printf("请输入字符串:");
scanf("%s", str);
for (i = 0; i < strlen(str); i++) {
num[(int)str[i]]++;
}
for (i = 0; i < 256; i++) {
if (num[i] != 0) {
printf("字符%c出现%d次\n", (char)i, num[i]);
}
}
return 0;
}
```
2.使用计数器统计字符出现次数
```c
#include <stdio.h>
int main() {
char str[200];
int cnt[128] = {0};
int i;
printf("请输入字符串:");
gets(str);
for (i = 0; str[i] != '\0'; ++i) {
cnt[str[i]]++;
}
for (i = 0; i < 128; i++) {
if (cnt[i] != 0) {
printf("%c:%d\n", i, cnt[i]);
}
}
return 0;
}
```
统计字符出现的次数c语言
以下是一个统计字符出现次数的C语言程序示例:
```c
#include <stdio.h>
void countCharacter(char *str, char ch, int *count) {
while (*str != '\0') {
if (*str == ch) {
(*count)++;
}
str++;
}
}
int main() {
char str[100];
char ch;
int count = 0;
printf("请输入一个字符串:");
scanf("%s", str);
printf("请输入要统计的字符:");
scanf(" %c", &ch);
countCharacter(str, ch, &count);
printf("字符 %c 在字符串 %s 中出现了 %d 次。\n", ch, str, count);
return 0;
}
```
该程序中,我们定义了一个`countCharacter`函数来统计字符串中特定字符的出现次数。函数接收三个参数:一个指向字符串的指针`str`、要统计的字符`ch`和用于存储出现次数的整数指针`count`。在函数中,我们使用了一个`while`循环来遍历字符串中的每个字符,如果当前字符等于要统计的字符,则将计数器加1。最后,我们在`main`函数中调用`countCharacter`函数,并输出统计结果。