This blog is under construction

Monday 15 July 2013

C program to find the number of unique characters in a string

Write C program to calculate the number of unique characters in a string.



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

  int main() {
        char input[256], output[256];
        int i, j, k = 0, flag, len;

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

        /* skip the duplicates and store the unique characters in output */
        for (i = 0; i < strlen(input); i++) {
                flag = 0;
                for (j = i + 1; j < strlen(input); j++) {
                        if (input[i] == input[j]) {
                                flag = 1;
                                break;
                        }
                }

                /* storing unique characters alone */
                if (!flag)
                        output[k++] = input[i];
        }
        output[k] = '\0';

        /* len - gives number of unique characters in the given string */
        len = strlen(output);

        /* print the unique characters and number of unique characters */
        printf("Number of unique characters in the given string: %d\n", len);
        printf("Unique Characters In The Given String: %s\n", output);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input string: helloworld
  Number of unique characters in the given string: 7
  Unique Characters In The Given String: heworld


No comments:

Post a Comment