Home Strings Write a program to find the character having the maximum frequency in a string?

Write a program to find the character having the maximum frequency in a string?

by nikoo28
0 comment

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.


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:-

#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
		//ignoring white spaces
		if(*str == ' ')

		//incrementing the value of the array at the ASCII value of character

		//incrementing the pointer in string

	int i=0;

	// to get the maximum frequency and the index of character
	int max = -1;
	int char_max_index = 0;

 		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);

	printf("The maximum occuring character is:- %c",maxFreq(arr,str));

	return 0;
0 comment

You may also like

Enclose codes in [code lang="JAVA"] [/code] tags

This site uses Akismet to reduce spam. Learn how your comment data is processed.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More