Understanding the Problem:
Before we start writing code, it’s crucial to understand the problem at hand.
We want to create a C# program that takes a string as input and produces a count of each unique character in that string.
Table of Contents
Code Example 1: Program to find Character Occurrence in a String in C#
Let’s start with a simple approach using a dictionary to store character occurrences.
Below is the C# program to count the occurrences of each character in a String.
using System;
using System.Collections.Generic;
class CharacterCounter
{
static void Main()
{
string inputString = "hello world";
Dictionary<char, int> charCount = new Dictionary<char, int>();
foreach (char c in inputString)
{
// Exclude spaces from character count
if (c != ' ')
{
if (charCount.ContainsKey(c))
charCount++;
else
charCount = 1;
}
}
// Display the results
foreach (var entry in charCount)
{
Console.WriteLine($"Character '{entry.Key}' occurs {entry.Value} times.");
}
}
}
Output:
Character 'h' occurs 1 times.
Character 'e' occurs 1 times.
Character 'l' occurs 3 times.
Character 'o' occurs 2 times.
Character 'w' occurs 1 times.
Character 'r' occurs 1 times.
Character 'd' occurs 1 times.
Code Explanation:
- We use a
Dictionary<char, int>
to store characters and their corresponding counts. - The
foreach
loop iterates through each character in the input string. - We check if the character is already a key in the dictionary. If yes, we increment its count; otherwise, we add it with a count of 1.
- Finally, we iterate through the dictionary to display the results.
Code Example 2: Count occurrences of each character Using LINQ
In the below code example, we will count each unique character in the string using LINQ (Language Integrated Query).
using System;
using System.Linq;
class CharacterCounter
{
static void Main()
{
string inputString = "hello world";
var charCount = inputString
.Where(c => c != ' ') // Exclude spaces
.GroupBy(c => c)
.ToDictionary(g => g.Key, g => g.Count());
// Display the results
foreach (var entry in charCount)
{
Console.WriteLine($"Character '{entry.Key}' occurs {entry.Value} times.");
}
}
}
Code Explanation:
- We use LINQ’s
GroupBy
to group characters and thenToDictionary
to create our character count dictionary. - This approach is more concise and often preferred by most of the developers.
Example 3: Using a Char Array
We will use a character array to iterate through the string and update the character count.
In the below code example, we will find the Character Occurrence in a String in C#.
using System;
class CharacterCounter
{
static void Main()
{
string inputString = "Hello World";
// Remove empty spaces from the string
inputString = inputString.Replace(" ", string.Empty);
int[] charCount = new int[256]; // Assuming ASCII characters
foreach (char c in inputString)
{
charCount++;
}
// Display the results
for (int i = 0; i < 256; i++)
{
if (charCount[i] > 0)
{
Console.WriteLine($"Character '{(char)i}' occurs {charCount[i]} times.");
}
}
}
}
Output:
Character 'H' occurs 1 times.
Character 'W' occurs 1 times.
Character 'd' occurs 1 times.
Character 'e' occurs 1 times.
Character 'l' occurs 3 times.
Character 'o' occurs 2 times.
Character 'r' occurs 1 times.
Code Explanation:
- We use an integer array of size 256 to represent ASCII characters.
- The array is initialized to zeros.
- We iterate through the input string, and for each character, we increment the corresponding index in the array.
- Finally, we iterate through the array to display non-zero counts.
Programs you might also like:
- How to remove duplicate characters from a String in C#
- Leap Year Program in C, C++, C#, JAVA, PYTHON, and PHP
- Bubble sort programs in C, C++, JAVA, and PYTHON
- Program to copy all elements of an array into another array
- Program to print prime numbers from 1 to N
- Different Ways to Calculate Factorial in C# (with Full Code Examples)
- Fibonacci sequence: Fibonacci series in C# (with examples)
- Program to Convert Fahrenheit to Celsius: Algorithm, Formula, and Code Examples
- Converting Celsius to Fahrenheit in C#
- Different Ways to Calculate Factorial in C# (with Full Code Examples)
- C# Tutorial
- Difference Between Array And ArrayList In C#: Choosing the Right Collection - May 28, 2024
- C# Program to Capitalize the First Character of Each Word in a String - February 21, 2024
- C# Program to Find the Longest Word in a String - February 19, 2024