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 Blogs - https://code-sample.com and https://code-sample.xyz
My Book1 - BEST SELLING ANGULAR BOOK (INCLUDING ALL VERSIONS 2, 4, 5, 6, 7)
My Book2 - ANGULAR 2 INTERVIEW QUESTIONS BOOK - Both Books are Available on WorldWide.

www.code-sample.com/. Powered by Blogger.