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.


freq of char in string


Related Post

Leave a Reply