1

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); } 
4
  • possible duplicate of C program for removing duplicate characters in a string...Shows run time error Commented May 4, 2014 at 19:17
  • 2
    main()'s signature is not main() but either int main(void) or int main(int, char **) (on a hosted implementation). Also, do use whitespace. But do NOT use gets(), because it is inherently insecure. Use fgets() instead. Commented May 4, 2014 at 19:18
  • @jycr753 as a general rule, it seems unhelpful to use debugging questions as dupe closure targets for "how should I implement this?" questions. Even if it's possible to piece together a solution from the linked question and its answers, it's unlikely to provide the best solution and the two questions are asking fundamentally different things. Commented May 4, 2014 at 20:55
  • @MarkAmery Its hard to pick since there is a lot references to something similar, since it just need a bit more of research to find it... Commented May 4, 2014 at 21:02

2 Answers 2

2

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)); } } 
Sign up to request clarification or add additional context in comments.

2 Comments

i don't want to print the repeated characters.so i want to remove all the repeated characters...so i want to print those non-repetitive characters in string.
@Kumar2080 And that's exactly what my code does. Read the first sentence in my answer. This code only prints out the characters which are not repeated.
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; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.