Fiery Phoenix Fiery Phoenix - 10 days ago 7
C# Question

Returning Most Frequent Character(s) in a String

Trying to achieve this using a Dictionary. Currently, I have this method:

/// <summary>
/// Returns the character(s) with the highest occurence in this string.
/// </summary>
/// <param name="str">the tring containing the characters</param>
/// <returns>the character or characters with the highest occurence</returns>
static char[] GetMostFrequentChar(string str)
var chars = new Dictionary<char, int>();
List<char> mostCommon = new List<char>();
for (int i = 0; i < str.Length; i++)
if (chars.ContainsKey(str[i]))
int curr = chars[str[i]];
chars[str[i]] = curr + 1;
} else // character not in dictionary
chars.Add(str[i], 1); // initial count for an added character is 1
foreach (KeyValuePair<char, int> entry in chars)
if (entry.Value == chars.Keys.Max())
char[] result = mostCommon.ToArray();
return result;

It's supposed to return an array containing the most frequent character(s), but I seem to get an empty array whenever I run this method on an input string. Where did I go wrong?

I know there are ways to do it without a Dictionary, but I'm curious how it works with a Dictionary.


Kevin Gosse already give you the answer, but you could simplify your code a bit like this:

private static char[] GetMostFrequentChar(string str)
    Dictionary<char, int> chars = new Dictionary<char, int>();

    foreach (char c in str)
        if (chars.ContainsKey(c)) chars[c]++;
        else chars.Add(c, 1);

    int max = chars.Values.Max();
    return chars.Where(b => b.Value == max).Select(b => b.Key).ToArray();