This blog is under construction

Thursday 18 July 2013

C program to remove duplicate words in a string

Write a C program to print unique words in a string.


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

  int main() {
        char string[256], text[256], words[100][256];
        int i, j, k, n;

        i = j = k = n = 0;

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

        /* copying each and every word from the string */
        while (string[i] != '\0') {
                if (string[i] == ' ') {
                        words[j][k] = '\0';
                        k = 0;
                        j++;
                } else {
                        words[j][k++] = string[i];
                }
                i++;
        }

        words[j][k] = '\0';
        n = j;

        /* remove duplicate words in the given string */
        for (i = 0; i < n; i++) {
                for (j = i + 1; j <= n; j++) {
                        if (strcmp(words[i], words[j]) == 0) {
                                for (k = j; k < n; k++) {
                                        strcpy(words[k], words[k + 1]);
                                }
                                n--, j--;
                        }
                }
        }

        /* print the unique words */
        for (i = 0; i <= n; i++) {
                printf("%s ", words[i]);
        }

        printf("\n");
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input string:hello world hello world hello hello hell
  hello world hell 


2 comments:

  1. in this prgrm to produce the wrong answer....!!!

    string[strlen(string) - 1] = '\0';

    to change in ...!!!

    string[strlen(string)] = '\0';

    ReplyDelete
  2. in these program should not print correct answer...!!!

    then their are problem is..,,

    string[strlen(string) - 1] = '\0';

    it will be change in ..

    string[strlen(string)] = '\0';

    thnk you to give tht prgrm...;)

    ReplyDelete