C# How To Count Character Frequency
Count Character Frequency
Use a Dictionary to count how many times each character appears in a string:
Example
string text = "hello";
Dictionary<char, int> counts = new Dictionary<char, int>();
foreach (char c in text)
{
if (counts.ContainsKey(c))
{
counts[c]++;
}
else
{
counts[c] = 1;
}
}
foreach (KeyValuePair<char, int> item in counts)
{
Console.WriteLine(item.Key + ": " + item.Value);
}
Explanation:
Each character is a key in the dictionary, and its count is the value.
If the character is already in the dictionary, counts[c]++ adds 1 to its count. If not, it is added with the count 1.