How to remove duplicates from a string in C

1 Answer

0 votes
#include <stdio.h>

char* removeDuplicates(char str[]) {
    int index = 0;
  
    for (int i = 0; str[i] != '\0'; i++) {
        int j;
        for (j = 0; j < i; j++) {
            if (str[i] == str[j]) { // character already exist
                break;
            }
        }
  
        if (j == i) {
            str[index++] = str[i];
        }
    }
  
    str[index] = '\0';
  
    return str;
}
  
int main() {
    char str[] = "abcdaaaabbbccccddddefghhhhhhxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
  
    removeDuplicates(str);
  
    puts(str);
  
    return 0;
}
  
  
  
  
/*
run:
  
abcdefghx
  
*/

 



answered Feb 9, 2024 by avibootz
edited Feb 9, 2024 by avibootz

Related questions

...