Remove Duplicate Characters from a String

Code

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

void remove_duplicates(char *str) {
    int i = 0;
    while (str[i] != '\0') ++i;

    for (int j = 0; j < i; ++j) {
        for (int k = j + 1; k < i; ) {
            if (str[j] == str[k]) {
                // Dịch trái
                for (int m = k; m < i; ++m) {
                    str[m] = str[m + 1];
                }
                --i;      // chuỗi ngắn lại
            } else {
                ++k;
            }
        }
    }
}

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