Remove Duplicate Characters from a String

Code

#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdbool.h>

void remove_duplicates(char *str) {
    bool seen[256] = {false};  // Track all possible ASCII characters
    int index = 0;             // Position to place next unique character

    for (int i = 0; str[i] != '\0'; i++) {
        unsigned char ch = str[i];  // Ensure proper indexing for extended ASCII
        if (!seen[ch]) {
            seen[ch] = true;
            str[index++] = ch;      // Keep first occurrence
        }
    }
    str[index] = '\0';  // Null-terminate the modified string
}



int main() {
    char str[101];
    fgets(str, sizeof(str), stdin);

    // Remove newline
    uint8_t i = 0;
    while (str[i]) {
        if (str[i] == '\n') {
            str[i] = '\0';
            break;
        }
        i++;
    }

    remove_duplicates(str);
    printf("%s", str);
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

programming

Expected Output

progamin