removing all repeated characters from string in c

牧云@^-^@ 提交于 2021-02-11 07:49:41

问题


I want to remove all the repeated characters from a string. For example, if I have:

"abcdabef"

I want the result to be

"cdef"

I have tried with loops, but it's getting me confusing. Can anyone just tell me how to do this?

Here's what I've tried so far:

#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);
}

回答1:


If I were you, I would just count the characters in the string and print out those which appear exactly once in the string.

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));
    }
}



回答2:


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;
}


来源:https://stackoverflow.com/questions/23460454/removing-all-repeated-characters-from-string-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!