如何让字符在C中以正确的顺序出现?

How to make characters appear in the correct order in C?

我有一个 C 程序,用于 return 给定输入字符串中的重复字符及其出现频率。目前,它工作正常,但我想知道是否有一种方法可以更改它,以便 return 个字符按出现顺序排列,而不是按字母顺序(?)排列。

# include <stdio.h>
# include <stdlib.h>
#include <ctype.h>
# define NO_OF_CHARS 256

char fillCharCounts(unsigned char *str, int *count)
{
   int i;
   for (i = 0; *(str+i);  i++)
      count[*(str+i)]++;
return 0;
}

void printDups(unsigned char *str)
{
  int *count = (int *)calloc(NO_OF_CHARS,
                             sizeof(int));
  fillCharCounts(str, count);


int dupe_chars = 0; 
int i;
    for (i = 0; i < NO_OF_CHARS; i++)
        if (count[i] > 1) {
            printf ("\nDuplicate letter: %c, Occurrences: %d", i, count[i]);
            ++dupe_chars; 
        }

    if (0 != dupe_chars)
        printf ("\n");        
    else
        printf ("\nNo duplicates found\n");

  free(count);
}

int main()
{
    unsigned char str[15] = "";
    printf("Enter a word>");
    scanf("%s", str);
    printDups(str);
    getchar();

return 0;
}

目前,如果输入字符串是“zzbbaa”,它会给出输出;

“重复:a,计数:2” “重复:b,计数:2” “重复:z,计数:2”

如何更改此设置,以便输出 return 重复项在字符串中的出现顺序?

您可以再次检查该字符串,打印出第一次找到的副本。

这是我编写的代码。不需要动态分配内存——count数组可以入栈,*(str + i)写成str[i].

要好得多
#include <stdio.h>
#include <limits.h>

void printDups(unsigned char *s) {
    int count[UCHAR_MAX+1] = {0};
    int dupes = 0;
    for (int i = 0; s[i]; i++) {
        count[s[i]]++;
        dupes = dupes || (count[s[i]] > 1);
    }
    for (int i = 0; s[i]; i++) {
        if (count[s[i]] > 1) {
            printf("Duplicate letter: %c, Occurrences: %d\n", s[i], count[s[i]]);
            count[s[i]] = 0;
        }
    }
    if (!dupes) {
        printf("No duplicates found\n");
    }
 }

int main(int argc, char**argv) {
    unsigned char s[] = "hello world";
    printDups(s);
}