Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C# program to count the occurrences of each character
Counting character occurrences in a string is a common programming task in C#. This can be accomplished using various approaches, from basic loops to modern LINQ methods and dictionary-based solutions.
Using Basic Loop with String Manipulation
The first approach uses a while loop and string replacement to count occurrences −
using System;
public class Demo {
public static void Main() {
string str = "Website";
Console.WriteLine("String: " + str);
while (str.Length > 0) {
Console.Write(str[0] + " = ");
int count = 0;
char currentChar = str[0];
for (int j = 0; j < str.Length; j++) {
if (str[0] == str[j]) {
count++;
}
}
Console.WriteLine(count);
str = str.Replace(currentChar.ToString(), string.Empty);
}
}
}
The output of the above code is −
String: Website W = 1 e = 2 b = 1 s = 1 i = 1 t = 1
Using Dictionary for Character Counting
A more efficient approach uses a Dictionary to store character counts −
using System;
using System.Collections.Generic;
public class CharacterCounter {
public static void Main() {
string str = "Programming";
Console.WriteLine("String: " + str);
Dictionary<char, int> charCount = new Dictionary<char, int>();
foreach (char c in str) {
if (charCount.ContainsKey(c)) {
charCount[c]++;
} else {
charCount[c] = 1;
}
}
foreach (var pair in charCount) {
Console.WriteLine(pair.Key + " = " + pair.Value);
}
}
}
The output of the above code is −
String: Programming P = 1 r = 2 o = 1 g = 2 a = 2 m = 2 i = 1 n = 1
Using LINQ GroupBy Method
The most concise approach uses LINQ's GroupBy method −
using System;
using System.Linq;
public class LinqCharCount {
public static void Main() {
string str = "Hello World";
Console.WriteLine("String: " + str);
var charGroups = str.GroupBy(c => c)
.OrderBy(g => g.Key);
foreach (var group in charGroups) {
Console.WriteLine(group.Key + " = " + group.Count());
}
}
}
The output of the above code is −
String: Hello World = 1 H = 1 W = 1 d = 1 e = 1 l = 3 o = 2 r = 1
Comparison of Methods
| Method | Time Complexity | Space Complexity | Best Use Case |
|---|---|---|---|
| Basic Loop | O(n²) | O(1) | Learning purposes, small strings |
| Dictionary | O(n) | O(k) where k = unique chars | Large strings, performance critical |
| LINQ | O(n) | O(k) where k = unique chars | Readable code, modern applications |
Conclusion
Character counting in C# can be implemented using basic loops, dictionaries, or LINQ methods. The dictionary approach offers the best performance with O(n) complexity, while LINQ provides the most readable and concise solution for modern C# applications.
