Monday, March 14, 2022

C# Count each letter in a sentence

Create a console application.


using System;
using System.Collections.Generic;
namespace CountLetters
{
    class Program
    {
        static void Main(string[] args)
        {
            string name = "AABBCCDEFAJEET";
            char[] letters = name.ToCharArray();
            
            Dictionary dic = new Dictionary();
            for (int i = 0; i < letters.Length; i++)
            {
                int count = Array.FindAll(letters, x => x == letters[i]).Length;
                if (!dic.ContainsKey(letters[i]))
                {
                    dic.Add(letters[i], count);
                }
            }
            foreach (var item in dic)
            {
                Console.WriteLine("{0} {1}", item.Key, item.Value);
            }
            Console.ReadKey();
        }
    }
}
OUTPUT
A 3
B 2
C 2
D 1
E 3
F 1
J 1
T 1

No comments:

Post a Comment

Hot Topics