Remove Duplicate Characters from a String

Code

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

void remove_duplicates(char *str) {
	char no_dup[101];
    int index;
    int no_dup_index;

    // create no duplicate version of the string
    while (str[index] != '\0') {
        char c = str[index];

        // search for c in str before index
        int found = 0;
        for (int i = 0; i < index; i++) {
            found = str[i] == c;
            if (found) {
                break;
            }
        }

        // add c to no duplicate if not found
        if (!found) {
            no_dup[no_dup_index++] = c;
        }

        // process next char
        index++;
    }

    // copy no duplicate back to original string
    no_dup[no_dup_index] = '\0';
    while (no_dup_index >= 0) {
        str[no_dup_index] = no_dup[no_dup_index];
        no_dup_index--;
    }
}

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