Frequency of characters in a String - C Programming Tutorial

In this c programming tutorial we are going to see program which computes frequency of characters in a string i.e. which character is present how many times in a string. For example in the string "krishna" each of the character 'k', 'r', 'i','s','h','n', and 'a' has occurred one time. Note that only lower case alphabets are considered, other characters (uppercase and special characters) are ignored. For counting number of characters in a string we need to traverse the whole string from its start to end and store the count for each character that appears in string. For storing character count we can use simple integer array with name say "count" and having size 26 as there are only 26 alphabets (we are ignoring special symbols and uppercase characters).
Now to make program efficient we are making use of ASCII values of characters. See the "count[string[c]-'a']++" statement in code, consider input string begins with 'a' so c is 0 initially and string[0] = 'a' and string[0]-'a' = 0 (see ASCII codes for respective characters if you are still confused) and we increment count[0] i.e. a has occurred one time and repeat this till complete string is scanned and that's it, afterward we simply printed the values in count[] array if its not equals to zero. You can easily modify this program to handle uppercase and special symbols.
Following is the complete C programming code for computing frequency of characters in a string.
#include <stdio.h>
#include <string.h>
int main()
{
   char string[100];
   int c = 0, count[26] = {0};
   printf("Enter a string\n");
   gets(string);
   while (string[c] != '\0')
   {
      /** Considering characters from 'a' to 'z' only
          and ignoring others */
      if (string[c] >= 'a' && string[c] <= 'z')
         count[string[c]-'a']++;
      c++;
   }
   for (c = 0; c < 26; c++)
   {
      /** Printing only those characters
          whose count is at least 1 */
      if (count[c] != 0)
         printf("%c occurs %d times in the entered string.\n",c+'a',count[c]);
   }
   return 0;
}

 Output:

freq of char in string

Comments

Popular posts from this blog

MATLAB code for Circular Convolution using Matrix method

Positive number pipe in angular 2+