Character Frequency Counter with a Dictionary
csharpC# and .NETbeginnerinterview-prep
Count how often each character appears using Dictionary of char to int, then print the most frequent first.
var counts = CountCharacters("hello world");
foreach (var (character, count) in counts.OrderByDescending(p => p.Value).ThenBy(p => p.Key))
Console.WriteLine($"'{character}': {count}");
// O(n) time. GetValueOrDefault returns 0 for a character that has not been seen yet.
static Dictionary<char, int> CountCharacters(string text)
{
var counts = new Dictionary<char, int>();
foreach (char c in text)
{
if (c == ' ') continue;
counts[c] = counts.GetValueOrDefault(c) + 1;
}
return counts;
}