C# program to return highest occurred character in a String
Here's a C# program that returns the character with the highest occurrence in a given string:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
string inputString = "Hello, World!";
char highestOccurredChar = GetHighestOccurredCharacter(inputString);
Console.WriteLine("Highest occurred character: " + highestOccurredChar);
}
static char GetHighestOccurredCharacter(string inputString)
{
Dictionary charCount = new Dictionary();
// Count the occurrences of each character in the string
foreach (char c in inputString)
{
if (charCount.ContainsKey(c))
{
charCount[c]++;
}
else
{
charCount[c] = 1;
}
}
int maxCount = 0;
char highestOccurredChar = '\0';
// Find the character with the highest occurrence
foreach (KeyValuePair pair in charCount)
{
if (pair.Value > maxCount)
{
maxCount = pair.Value;
highestOccurredChar = pair.Key;
}
}
return highestOccurredChar;
}
}
In this program, we use a 'Dictionary' called 'charCount' to store the count of each character in the input string. We iterate through each character in the string and update its count in the dictionary.
Next, we initialize variables 'maxCount' and 'highestOccurredChar' to keep track of the character with the highest occurrence. We iterate over the dictionary and compare the count of each character with the current maximum count. If a character has a higher count, we update maxCount and highestOccurredChar accordingly.
Finally, we return the 'highestOccurredChar', which represents the character with the highest occurrence in the string.
In the example above, the output would be:
Highest occurred character: l
The character 'l' occurs three times, which is the highest occurrence in the input string "Hello, World!".