This blog is under construction

Wednesday 17 July 2013

C program to remove duplicates characters in a string

Write a C program to remove duplicates characters in a string.


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

  int main() {
        char str[256];
        int i, j, k, ch, flag;

        /* get the input string from the user */
        printf("Enter your input string:");
        fgets(str, 256, stdin);
        str[strlen(str) - 1] = '\0';

        /* delete the duplicate characters in i/p string */
        while (str[i] != '\0') {

                /* ch is the current processing character */
                ch = str[i];

                /*
                 * checking whether ch is present in the
                 * remaining part of the string.  If yes,
                 * delete it
                 */
                j = i + 1;
                while (str[j] != '\0') {
                        if (str[j] == ch) {
                                k = j;
                                /* remove duplicates */
                                while (str[k] != '\0') {
                                        str[k] = str[k + 1];
                                        k++;
                                }
                        } else {
                                j++;
                        }
                }
                i++;
        }

        /* print the result */
        printf("After removing duplicates: %s\n", str);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input string : aaabbaccaddeefghhiikaalm
  After removing duplicates: abcdefghiklm


4 comments: