Question: We are given an input string, and we need to find the character with the maximum frequency.
Input:- “This is an sample string.”
Output:- The character with maximum frequency is :- i
The logic of this problem is very simple, we need to scan the string and store the frequency of each of the character. For this we can use the ASCII code of the characters which is a separate integer. Note that character are not only the English alphabets. !@#$ are also characters.
To extend our program to support the feature for these characters as well we can declare an integer array of 256 , since the range of char is 256, we will then scan the string and increment the value at each ASCII value. Example:- if we scan “n”, then we will do arr[(int)n]++. That means we make an increment at the ASCII value of n.
ALGORITHM:-
Input string = “test”
1: Construct character count array from the input string.
count['e'] = 1
count['s'] = 1
count['t'] = 2
2: Return the index of maximum value in count array (returns ‘t’).
Here is an implementation of the above example:-
#include #define NO_OF_CHARS 256 //defining a function to find the character with maximum frequency char maxFreq(int *arr, char *str) { // loop until we reach the end while(*str!='\0') { //ignoring white spaces if(*str == ' ') { str++; continue; } //incrementing the value of the array at the ASCII value of character arr[*str]++; //incrementing the pointer in string str++; } int i=0; // to get the maximum frequency and the index of character int max = -1; int char_max_index = 0; for(i=0;i<NO_OF_CHARS;i++) if(arr[i] > max) { max = arr[i]; char_max_index = i; } // return the character having maximum frequency return ((char)char_max_index); } int main(void) { int *arr = (int *)malloc(sizeof(int)*NO_OF_CHARS); char *str = (char *)malloc(sizeof(char)*100); scanf("%[^\n]s",str); printf("The maximum occuring character is:- %c",maxFreq(arr,str)); return 0; }