// C++ program to output the maximum occurring character in a string
#include<bits/stdc++.h>
#define ASCII_SIZE 256
using namespace std;
char getMaxOccuringChar(char* str)
{
int count[ASCII_SIZE] = {0};//create an array to keep character count and initialize it to 0
int len = strlen(str); //length of string
for (int i=0; i<len; i++) //loop for character count
count[str[i]]++;
int max = -1; // Initialize max count
char result; // Initialize result
for (int i = 0; i < len; i++)
{
if (max < count[str[i]]) //comparing a maximum count with each character count
{
max = count[str[i]]; //assign character count to max value if condition is true
result = str[i]; //assign maximum character count character to result
}
}
return result;
}
int main()
{
char str[] = "sample string";
cout << "Max occurring character is " << getMaxOccuringChar(str);
}
Output:
Max occurring character is s
Explanation:
In the above program, a function getMaxOccuringChar() is defined in which a string is passed, an array count of size 256 is defined as there are 255 characters. The logic behind above program is evaluating length of passed string and running a for loop till string length, within for loop count array is incremented for each character in the string hence providing character count for each character. Finally, a max value is initialized to -1 and compared with each character count to get maximum character count within string. Maximum character count character is stored in result variable and is returned from function.
0 Comment(s)