How to remove duplicate characters from a string in C

2 Answers

0 votes
#include <stdio.h>
#include <string.h>
     
void remove_duplicate_characters(char *s) {
    int len = strlen(s);
    
    for (int i = 0; i < len; i++) {
        for (int j = i + 1; s[j] != '\0'; j++) {
            if (s[j] == s[i] && s[j] != ' ') {
                strcpy(s + j, s + j + 1);
                j--;
            }
        }
    }
}
  
int main() {
    char s[64] = "ccc x ppppprooooogggramming x c dddd";
    
    remove_duplicate_characters(s);
        
    puts(s);
}
    
    
     
/*
run:
     
c x progamin   d
    
*/

 



answered Apr 3, 2019 by avibootz
edited Mar 5 by avibootz
0 votes
#include <stdio.h>
#include <string.h>
#include <stdbool.h>

void RemoveDuplicateCharacters(char *str) {
    bool seen[256] = { false };   // Track ASCII characters
    int writeIndex = 0;

    for (int readIndex = 0; str[readIndex] != '\0'; readIndex++) {
        unsigned char c = str[readIndex];
        if (!seen[c]) {
            seen[c] = true;
            str[writeIndex++] = c;   // Keep first occurrence
        }
    }

    str[writeIndex] = '\0';  // Null‑terminate the new string
}

int main() {
    char s[] = "ccc x ppppprooooogggramming x c dddd";
    
    RemoveDuplicateCharacters(s);
    
    printf("%s\n", s);   
    
    return 0;
}


      
/*
run:

c xprogamind
      
*/

 



answered Mar 5 by avibootz
...