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

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


ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..

My Tech Blog - https://www.code-sample.com/
My Books - Book 1 and Book 2

Count character occurrence of a string using dictionary KeyValuePair C#? Count character occurrence of a string using dictionary KeyValuePair C#? Reviewed by Anil Singh on 9:10 PM Rating: (5)
www.code-sample.com/. Powered by Blogger.
^