Remove Duplicate Characters from a String

Code

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

void remove_duplicates(char *str) {
	//Your logic here
    uint8_t write_index =0;
    uint8_t letter_index =0;
    //start scanning string char by char until null termination TODO: add length check validation
    while(str[letter_index]!='\0'){
        // copy original char
        char og_c = str[letter_index];
        bool unique_flag = true;
        for(uint8_t i=0; i<letter_index; i++){
            if(str[i]==og_c){
                // this letter has reoccured so advance to the next letter
                unique_flag = false;
                break;
            }
        }
        if(unique_flag){
            str[write_index] = og_c;
            write_index++;
        }
        letter_index++;

    }

    // null terminate final string
    str[write_index] = '\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