Skip to main content

Count character occurrence of a string using dictionary KeyValuePair C#?

Hello everyone, I am going to share the code sample for find and count the characters of a string using dictionary key value pair. The example as given below.

/// <summary>
/// </summary>
public class CountCharsOccurrence
{
    static void Main(string[] a)
    {
        Dictionary<char, int> dicList = new Dictionary<char, int>();
        Console.WriteLine("Enter charater sting");

        foreach (var chr in Console.ReadLine())
        {
            int count = 0;
            if (dicList.ContainsKey(chr))
            {
                count = dicList[chr];
            }
            dicList[chr] = count + 1;
        }

        foreach (KeyValuePair<char, int> pair in dicList)
        {
            Console.WriteLine(pair.Key + " = " + pair.Value);
        }
        Console.ReadLine();
    }
}

The live output as given below