Remove Duplicate Characters from a String

Code

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

void remove_duplicates(char *str) {
	int len = 0;
    while(str[len]) len++;

    int nd_rmv[101] = {0};
    int i = 0;
    while(str[i]) {
        for(int j = i + 1; j < len; j++) {
            if(str[i] == str[j]) nd_rmv[j]++;
        }
        i++;
    }

    char new_str[101];
    int new_idx = 0;
    for(int k = 0; k < len; k++) {
        if(nd_rmv[k] == 0) {
            new_str[new_idx] = str[k];
            new_idx++;
        }
    }
    new_str[new_idx] = '\0';
    
    int l = 0;
    while (new_str[l]) {
        str[l] = new_str[l];
        l++;
    }
    str[l] = '\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