Count the frequency of each character in a string with C.
#include <stdio.h>
#include <string.h>
int main()
{
char str[100];
int i, len;
int freq[26];
printf("Enter any string: ");
gets(str);
len = strlen(str);
for (i = 0; i < 26; i++)
{
freq[i] = 0;
}
/* Find total number of occurrences of each character */
for (i = 0; i < len; i++)
{
/* If the current character is lowercase alphabet */
if (str[i] >= 'a' && str[i] <= 'z')
{
freq[str[i] - 97]++;
}
else if (str[i] >= 'A' && str[i] <= 'Z')
{
freq[str[i] - 65]++;
}
}
/* Print the frequency of all characters in the string */
printf("\nFrequency of all characters in the given string: \n");
for (i = 0; i < 26; i++)
{
/* If current character exists in given string */
if (freq[i] != 0)
{
printf("'%c' = %d\n", (i + 97), freq[i]);
}
}
return 0;
}
Output
Enter any string : Learn with Rezaul karim
Frequency of all characters in the given string :
'a' = 3
'e' = 2
'h' = 1
'i' = 2
'k' = 1
'l' = 2
'm' = 1
'n' = 1
'r' = 3
't' = 1
'u' = 1
'w' = 1
'z' = 1
0 Comments