Remove Duplicate Characters from a String

Code

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

int str_leng(char *str){
    int leng = 0;
    while(str[leng] != '\0'){
        leng++;
    }
    return leng;
}

void stcpy(char *dest, char *str){
    int i = 0;
    while(str[i] != '\0'){
        dest[i] = str[i];
        i++;
    }
    dest[i] = '\0';
}

void remove_duplicates(char *str) {
	//Your logic here
    int leng = str_leng(str);
    int cnt = 0;
    
    for(int i = 0; i < leng; i++){
        for(int j = i + 1; j < leng; j++){
            if(str[i] == str[j]){
                str[j] = '|';
                cnt++;
            }
        }
    }
    
    char tmp[101];
    int j = 0;
    for(int i = 0; i < leng; i++){
      if(str[i] != '|'){
        tmp[j] = str[i];
        j++;
      }
    }
    tmp[j] = '\0';
    stcpy(str,tmp);
}

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