按用户输入 C 的顺序返回 ASCII 字符的计数



我需要按照 ASCII 字符在用户输入接收的字符数组中出现的顺序返回 ASCII 字符的计数

我当前的解决方案是按字符在 ASCII 表上出现的升序返回字符,而不是按用户输入的顺序返回字符

#include <stdio.h>
#include <string.h>
int main()
{
char string[16];
int c = 0, count[128] = {0}, x, counted = 0;
printf("Enter a word>n");
scanf("%s", string);
while (string[c] != '') {
if(string[c] >= '!' && string[c] <= '~'){
x = string[c] - '!';
count[x]++;
}
c++;
}
for (c = 0; c < 128; c++){
if(count[c] > 1){
printf("Duplicate letter: %c, Occurrences: %dn", c + '!', count[c]);
counted++;
}
}
if(counted < 1){
printf("No duplicates foundn");
}
return 0;
}

示例输入:

AAAAaaaBBBbb99

期望输出:

重复的字母:A,出现次数:4
重复的字母:a,出现次数:4
重复的字母: B, 出现次数: 3
重复的字母:b,出现次数:2
重复的信件: 9, 出现次数: 2

我当前(错误)的输出:

重复的信件: 9, 出现次数: 2
重复的字母:A,出现次数:4
重复的字母: B, 出现次数: 3
重复的字母:a,出现次数:4
重复的字母:b,出现次数:2


非常感谢这里的任何帮助

不是一个非常优雅的解决方案,但它有效:

#include <stdio.h>
#include <string.h>
int main() {
char string[1024];
int c = 0;
int count[128] = {0};
int x;
int counted = 0;
printf("Enter a word:n");
scanf("%1023s", string);
while (string[c] != '') {
if(string[c] >= '!' && string[c] <= '~'){
x = string[c] - '!';
count[x]++;
}
c++;
}
int j = 0;
while (string[j] != '') {
int ch = string[j] - '!';
if(count[ch] > 1){
printf("Duplicate letter: %c, Occurrences: %dn", ch + '!', count[ch]);
count[ch] = -1;
counted++;
}
j++;
}
if(counted < 1){
printf("No duplicates found.n");
}
return 0;
}

最新更新