DEV Community

Clever Cottonmouth
Clever Cottonmouth

Posted on

Counts the occurrences of each character in the string and then prints the character along with its count in c#.

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        string str = "hell";
        Dictionary<char, int> count = new Dictionary<char, int>();

        for (int i = 0; i < str.Length; i++)
        {
            char ch = str[i];
            if (count.ContainsKey(ch))
            {
                count[ch]++;
            }
            else
            {
                count[ch] = 1;
            }
        }

        foreach (var pair in count)
        {
            Console.WriteLine($"{pair.Key}, {pair.Value}");
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)