C program to find the frequency of characters in a string
Given a string S containing lowercase English characters, the task is to find the frequency of all the characters in the string.
Examples
Input: S="geeksforgeeks"
Output:
e - 4
f - 1
g - 2
k - 2
o - 1
r - 1
s - 2
Input: S="gfg"
Output:
f - 1
g - 2
Approach
Follow the steps to solve the problem:
- Initialize an array freq[] to store the frequency of each alphabet in the given string. The 0th index stores the frequency of the character ‘a’, the 1st index stores the frequency of the character ‘b’, and so on.
- Iterate over the given string S and increment the frequency of each character encountered by 1, by performing freq[S[i] – ‘a’] += 1. If S[i] = ‘a’, then S[i] – ‘a’ is equal to 0, therefore the frequency of ‘a’ is incremented in the array.
- After complete traversal of the string, print the frequency of all the characters in the string by traversing the array freq[].
Below is the implementation of the above approach:
C
#include <stdio.h>
#include <string.h>
void printFrequency( int freq[])
{
for ( int i = 0; i < 26; i++)
{
if (freq[i] != 0)
{
printf ( "%c - %d\n" ,
i + 'a' , freq[i]);
}
}
}
void findFrequncy( char S[])
{
int i = 0;
int freq[26] = { 0 };
while (S[i] != '\0' ) {
freq[S[i] - 'a' ]++;
i++;
}
printFrequency(freq);
}
int main()
{
char S[100] = "geeksforgeeks" ;
findFrequncy(S);
}
|
Output:
e - 4
f - 1
g - 2
k - 2
o - 1
r - 1
s - 2
Complexity of the above method
Time Complexity: O(N)
Auxiliary Space: O(26)
Last Updated :
01 Jun, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...