This blog is under construction

Wednesday 17 July 2013

C program to print the duplicates in a string

Write a C program to print the duplicates in a string and also find the frequency of duplicates.



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

  int main() {
        char myData[256];
        int i, index, dupCap[26] = {0}, dupSmall[26] = {0};

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

        /* calculate the occurance of small and caps characters */
        for (i = 0; i < strlen(myData); i++) {
                if (myData[i] >= 'a' && myData[i] <= 'z') {
                        index = myData[i] - 'a';
                        /* dupSmall - stores the occurance of each char */
                        dupSmall[index]++;
                } else if (myData[i] >= 'A' && myData[i] <= 'Z') {
                        index = myData[i] - 'A';
                        /* stores occurance of each CAPS character */
                        dupCap[index]++;
                }
        }

        /* print the duplicates */
        printf("Duplicate Char   Occurrence\n");
        for (i = 0; i < 26; i++) {
                /*
                 * if count corresponds to any character is greater
                 * than 1, then we have duplicates for that character
                 */
                if (dupCap[i] > 1) {
                        printf("\t%c\t => %d\n", i + 'A', dupCap[i]);
                }

                if (dupSmall[i] > 1) {
                        printf("\t%c\t => %d\n", i + 'a', dupSmall[i]);
                }
        }
        printf("\n");
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input string : ApplicAtion link
 Duplicate Char   Occurrence
A      => 2
i      => 3
l      => 2
n      => 2
p      => 2



No comments:

Post a Comment