DigestCPP

Lets Understand With Example

  • Home
  • Design Principal
  • Design Patterns
  • C++ 11 Features
  • C++11 Multithreading
  • Contact Us

Count Max occurrence of char in string

C++ Program to count Max occurrence of character in string:

Below program, I have done using map but they are many ways we can do below function.

source code:

/*
Program: Write Function return the char has max occurrence in string
Author: Alpha Master
Date: 14 Nov 2021
*/

//Header File
#include<iostream>
#include<map>

char maxOccurance(const std::string& str)
{
	std::map<char, int>map1;
	for(int i =0; i<str.size(); i++)
	{
		if(!(map1.find(str[i]) != map1.end()))
		{
			//std::cout<<"first time"<<str[i]<<std::endl;
			map1.insert({str[i], 1});
		}
		else
		{
			//need to increase the value
			//std::cout<<"Not first time"<<str[i]<<std::endl;
			int temp = map1[str[i]];
			++temp;
			map1[str[i]] = temp;
		}
	}
	char maxVal;
	int checkCount = 0;	
	//get the max value
	std::map<char, int>:: iterator itr = map1.begin();
	for(;itr!=map1.end();itr++)
	{
		if(itr->second > checkCount)
		{
			checkCount = itr->second;
			maxVal = itr->first;
		}
	}
	std::cout<<"Char:"<<maxVal<<std::endl;
	std::cout<<"count:"<<checkCount<<std::endl;
	return maxVal;
}


int main()
{
   	std::cout<<"Return the char has max occurance in string"<<std::endl;
	std::string input;
	std::cout<<"Enter the string"<<std::endl;
	std::cin>>input;
	maxOccurance(input);	
    	return 0;
}

Output:

Return the char has max occurance in string
Enter the string
absdgeaftyu
Char:a
count:2

Primary Sidebar




DigestCPP © 2023. All rights reserved.

    About Privacy Policy Terms and Conditions Contact Us Disclaimer