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

mirajhad

Clever Cottonmouth

Posted on January 17, 2024

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
πŸ’– πŸ’ͺ πŸ™… 🚩
mirajhad
Clever Cottonmouth

Posted on January 17, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related