Maximum Occuring Character Given a string str. The task is to find the maximum occurring character in the string str. If more than one character occurs the maximum number of time then print the lexicographically smaller character. code example
Example: c# + max char frequency in string
public static void Main(string[] args)
{
CharCounter("This is a neat day for Things about Coding9999");
}
public static void CharCounter(string str)
{
string strValidated = "";
str = str.Replace(" ", "");
if (Regex.IsMatch(str, @"^[A-Za-z0-9]+$")) strValidated = str;
else throw new FormatException("--------> Only Apha Numeric values allowed");
Dictionary<char, int> dict = new Dictionary<char, int>();
foreach (char c in strValidated)
{
if (dict.ContainsKey(c)) dict[c] = dict[c] + 1;
else dict.Add(c, 1);
}
var ordered = dict.OrderByDescending(x => x.Value)
.ToDictionary(d => d.Key, d => d.Value);
var result = ordered.Take(1)
.ToDictionary(d => d.Key, d => d.Value);
foreach (var item in result.Keys)
{
Console.WriteLine($"Key= {item} : Value= {result[item]}");
}
}