从c中删除字符串中的所有重复字符

时间:2014-05-04 19:15:08

标签: c string duplicates duplicate-removal

我想从字符串中删除所有重复的字符。例如,如果我有:

"abcdabef"

我希望结果是

"cdef"

我尝试过循环,但它让我感到困惑。谁能告诉我怎么做?

这是我迄今为止所做的尝试:

#include<stdio.h>
#include<string.h>
main()
{
    char s[20],ch,*p;
    int i,j,k,cnt;
    puts("enter string:");
    gets(s);
    for(i=0;s[i];i++)
    {
    ch=s[i];
    for(cnt=0,j=0;s[j];j++)
    {
            if(ch==s[j])
            cnt++;
            if(cnt>1)
            {
            for(k=0;s[k]==ch;k++)
            {
            strcpy(s+k,s+k+1);
            if(s[k]==ch)
            {k--;}
            }
            if(s[j-1]==ch)
            j--;
            }
    }
    }
    puts(s);
}

2 个答案:

答案 0 :(得分:2)

如果我是你,我只计算字符串中的字符并打印出字符串中恰好出现一次的字符。

char buf[BUFSIZE]; // whatever the size is

// get user input
if (!fgets(buf, sizeof buf, stdin))
    exit(EXIT_FAILURE); // couldn't fgets()

size_t len = strlen(buf);

int counts[1 << CHAR_BIT] = { 0 };

// count each character
for (size_t i = 0; i < len; i++) {
    unsigned char ch = buf[i];
    counts[ch]++;
}

// print those which are present exactly once
for (size_t i = 0; i < 1 << CHAR_BIT; i++) {
    if (counts[i] == 1) {
        printf("%c", (unsigned char)(i));
    }
}

答案 1 :(得分:1)

char* remRepeatedChars(char *str)
{
  char arr[128] = {0};
  char *tmp = str;

  while((*str) != '\0')
  {
    char *p = str;

    while(arr[*p] != 0 && *p != '\0')
      p++; // found repetition

    if(str != p) // the previous while was entered
      *str = *p; //Copy the content of p to str.

    arr[*str]++;    
    str++;
  }
  return tmp;
}