C program to find the frequency of characters in a string



C program to find the frequency of characters in a string

  • This program counts the frequency of characters in a given string. For Example the string is "hello", When the "l" occurs 2 times on the String.

Sample Code

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

int main()
{
    char string[100];
    int c = 0, count[26] = {0}, x;

    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') {
            x = string[c] - 'a';
            count[x]++;
        }

        c++;
    }

    for (c = 0; c < 26; c++)
        printf("%c occurs %d times in the string.\n", c + 'a', count[c]);

    return 0;
}

Output

Enter a string: 
welcome world
a occurs 0 times in the string.
b occurs 0 times in the string.
c occurs 1 times in the string.
d occurs 1 times in the string.
e occurs 2 times in the string.
f occurs 0 times in the string.
g occurs 0 times in the string.
h occurs 0 times in the string.
i occurs 0 times in the string.
j occurs 0 times in the string.
k occurs 0 times in the string.
l occurs 2 times in the string.
m occurs 1 times in the string.
n occurs 0 times in the string.
o occurs 2 times in the string.
p occurs 0 times in the string.
q occurs 0 times in the string.
r occurs 1 times in the string.
s occurs 0 times in the string.
t occurs 0 times in the string.
u occurs 0 times in the string.
v occurs 0 times in the string.
w occurs 2 times in the string.
x occurs 0 times in the string.
y occurs 0 times in the string.
z occurs 0 times in the string.



Related Searches to C program to find the frequency of characters in a string