Tech Point Fundamentals

Saturday, December 4, 2021

C# Program to Find the Character Having Max Occurrence in a String

C# Program to Find the Character Having Max Occurrence in a String

coding-interview-question-csharp

Most of the IT companies check the coding skills and problem-solving skills as well along with the theoretical interview questions. Sometimes you are free to write the pseudo code and sometimes you are asked to write the complete program either on any paper or any editor. 


This question is asked in the coding interview to write the program. Here you can find the program as well as a live running program so that you can test the program immediately.


Watch our videos here





Question: 


How can you find the character having maximum occurrence in a given string? Write a program to find the character having max count in a given string.



C# Program To Find the Character Having Max Count in a String


       
 

// Author 	: Tech Point Fundamentals
// Website 	: www.techpointfunda.com
// Channel	: https://www.youtube.com/c/TechPointFundamentals
// Demo		: Character Having Maximum Occurrence in String

using System;
using System.Collections.Generic;

public class Program
{
 public static void Main()
 {
   string inputString = "Tech Point Fundamentals";		
   int maxCharCount;
   char maxChar;
   MaxOccurrenceCharacter(inputString, out maxChar, out maxCharCount);
   
   Console.WriteLine("Input String : " + inputString);
   Console.WriteLine("Character Having Max Occurance : " + maxChar);
   Console.WriteLine("Character Max Count : " + maxCharCount);	
 }	  	
	
public static void MaxOccurrenceCharacter(string inputString, out char character, out int count)    
{  
  character = ' ';
  count = 0;		
  
  char[] charArray = inputString.ToLower().ToCharArray(); 
  
  Dictionary<char, int>countDictionary = new Dictionary<char, int>();
  
  for (int i = 0; i < charArray.Length; i++)
  {
  	if (charArray[i] != ' ')
  	{
  		if (!countDictionary.ContainsKey(charArray[i]))
  		{
  			countDictionary.Add(charArray[i], 1);
  		}
  		else
  		{
  			countDictionary[charArray[i]]++;
  		}
  	}
  }

  foreach (KeyValuePair<char, int> item in countDictionary)
  {
  	if (item.Value > count)
  	{
  		character = item.Key;
  		count = item.Value;
  	}
  }		
}	
}





Output: 

Input String : Tech Point Fundamentals
Character Having Max Occurance : t
Character Max Count : 3




Live Demo






No comments:

Post a Comment

Please do not enter any HTML. JavaScript or spam link in the comment box.