Saturday, July 21, 2012

Interview question (coding) : Remove duplicates from a string


Problem : Given a string, remove the duplicate characters.
example: BANANAS -> BANS
         bananas -> bans
         BaNanAs -> BaNnAs
         1232416 - > 12346
         
#include<stdio.h>
 
int main()
{
  char s1[10], s2[10];
  int i, j, c;
  s2[0] = '\0';
 
  printf("Enter the string : ");
  scanf("%s",s1);
 
  for(i = 0; s1[i] != '\0'; i++)
  {
    c = 0;
    for(j = 0; (s2[j] != '\0' && c == 0); j++)
    {
      if(s1[i] != s2[j])
        continue;
      else
        c = 1;
    } 
    if(c == 0)
    {
      s2[j++] = s1[i];
      s2[j] = '\0';
    }
  }
  printf("\nString after removing duplicates:%s\n", s2);

  return 0;
}

Written by

No comments:

Post a Comment