Write a C++ Program to Print Maximum Occurring Character in a String with an example. In this C++ example, we use the if statement within the for loop to get maximum character occurrence in a given string.
#include<iostream> #include<string> using namespace std; int main() { string str; int i, len; int max = -1; char result; int freq[256] = {0}; cout << "\nPlease Enter the String to Find Max Occur Char = "; getline(cin, str); len = str.length(); for(i = 0; i < len; i++) { freq[str[i]]++; } for(i = 0; i < len; i++) { if(max < freq[str[i]]) { max = freq[str[i]]; result = str[i]; } } cout<< "\nThe Maximum Occurring Character in " << str <<" = " << result; return 0; }
Please Enter the String to Find Max Occur Char = tutorial gateway
The Maximum Occurring Character in tutorial gateway = t
In this C++ maximum occurring string Character example, we used extra cout statements to show you the frequency of characters at each iteration.
#include<iostream> #include<string> using namespace std; int main() { string str; int i, len; int max = -1; char result; int freq[256] = {0}; cout << "\nPlease Enter the String to Find Max Occur Char = "; getline(cin, str); len = str.length(); for(i = 0; i < len; i++) { freq[str[i]]++; } for(i = 0; i < len; i++) { cout << "freq[str[i]] = " << freq[str[i]] << endl; cout << "str[i] = " << str[i] << endl; if(max < freq[str[i]]) { max = freq[str[i]]; cout << "Max = " << max << endl; result = str[i]; cout << "Result = " << result << endl; } cout << "-----\n\n"; } cout<< "\nThe Maximum Occurring Character in " << str <<" = " << result; return 0; }
C++ Program to Print Maximum Occurring Character in a String Example 3
#include<iostream> #include<string> using namespace std; int main() { string str; int i, len; int max = -1; char result; int freq[256] = {0}; cout << "\nPlease Enter the String to Find Max Occur Char = "; getline(cin, str); len = str.length(); for(i = 0; i < len; i++) { freq[str[i]]++; } for(i = 0; i < 256; i++) { if(freq[i] > freq[max]) { max = i; } } cout<< "\nThe Maximum Occurring Character in " << str <<" = " << (char)max; cout << "\nCharacter " << (char)max << " appears Maximum of " << freq[max] << " Times in " << str; return 0; }
Please Enter the String to Find Max Occur Char = hello world
The Maximum Occurring Character in hello world = l
Character l appears Maximum of 3 Times in hello world