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

Hey! I'm Anil Singh. I author this blog. I'm Active Blogger, Programmer. I love learning new technologies, programming, blogging and participating the forum discussions more...
My Blogs - http://www.code-sample.com and http://www.code-sample.xyz
My Books - Buy Books Online at Best Prices

You Might Also Like
Post a Comment
www.code-sample.com/. Powered by Blogger.