How to count occurrences of each letter in a char array with C#

1 Answer

0 votes
using System;
using System.Collections.Generic;

class CountLettersInCharArray
{
    static void Main()
    {
        char[] charArray = { 'C', '#', 'p', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'i', 'n', 'g' }; 
        Dictionary<char, int> letterCount = new Dictionary<char, int>();

        foreach (char c in charArray) {
            if (letterCount.ContainsKey(c)) {
                letterCount[c]++;
            }
            else {
                letterCount[c] = 1;
            }
        }

        foreach (var item in letterCount) {
            Console.WriteLine($"Letter {item.Key}: {item.Value} times");
        }
    }
}

 
 
/*
run:
     
Letter C: 1 times
Letter #: 1 times
Letter p: 1 times
Letter r: 2 times
Letter o: 1 times
Letter g: 2 times
Letter a: 1 times
Letter m: 2 times
Letter i: 1 times
Letter n: 1 times
     
*/
 

 



answered Mar 2, 2025 by avibootz
...