Featured Post

Trie implementation in C

Remove duplicate characters from a string

Here's a simple program to remove duplicate characters from an input string.

Function search(char* , char) finds the duplicates and return 1 if finds a duplicate and 0 otherwise.

Function removeDup(char*) actually removes the duplicates.

#include <stdio.h>
#include <malloc.h>
#include <string.h>

int search( char * arr, char item );

char* removeDup(char * input)
{
    char *res = (char*)malloc(strlen(input)+1);
    int i = 0,j=0  ;
   
    while(input[i] != '\0')
    {
        if (search(res,input[i]) == 0)
            res[j++] = input[i];
        i++;
    }
    
    return res;
}

int search( char * arr, char item )
{
    int i;
    for(i = 0 ; i < strlen(arr) ; i++)
        if(item == arr[i])
            return 1;
    return 0;
}

int main()
{
  char input[200];

  printf("\nEnter a string : ");
  scanf("%s",input);

  printf("\nOutput : %s\n" , removeDup(input));
}

Comments