-
Count Occurrences of Each Character
-
Counting how many times each character appears in a string is a common and essential programming task in C#. This concept is widely used in data processing, text analytics, algorithm design, and interview questions. Lets see the most common ways to solve this problem.
1. Count Occurrences of Each Character in C#
This is the simplest and most efficient method.
We use a
Dictionaryto store character counts.
Output:using System; using System.Collections.Generic; public class CharacterCountDemo { public static void Main(string[] args) { string input = "programming"; Dictionary<char, int> map = new Dictionary<char, int>(); foreach (char c in input) { if (map.ContainsKey(c)) map[c]++; else map[c] = 1; } foreach (var item in map) { Console.WriteLine($"{item.Key} : {item.Value}"); } } }p : 1 r : 2 o : 1 g : 2 a : 1 m : 2 i : 1 n : 1
2. Count Character Occurrences Using LINQ
Output:using System; using System.Linq; public class CharacterCountLinq { public static void Main(string[] args) { string input = "programming"; var result = input .GroupBy(ch => ch) .Select(g => new { Character = g.Key, Count = g.Count() }); foreach (var item in result) { Console.WriteLine($"{item.Character} : {item.Count}"); } } }p : 1 r : 2 o : 1 g : 2 a : 1 m : 2 i : 1 n : 1