Remove Duplicate Characters from a String

Code

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

void remove_duplicates(char *str) 
{
    if (str == NULL || *str == '\0') 
    {
        return;
    }

	bool seen[256] = {false};
    char * read_ptr = str;
    char * write_ptr = str;
    while (*read_ptr != '\0')
    {
        unsigned char curr_char = (unsigned char)(*read_ptr);
        if (!seen[curr_char])
        {
            seen[curr_char] = true;
            *write_ptr = *read_ptr;
            write_ptr++;
        }
        read_ptr++;
    }
    *write_ptr = '\0';
}

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