Character
Occurrence in a String in C#
In this article we will see the number of the character occurrence in a string.
private static void
CharactersOccurrence() {
Console.Write("Enter the string : "); string
inputString = Console.ReadLine();
inputString = inputString.Replace(" ", string.Empty); while
(inputString.Length > 0) {
Console.Write(inputString[0] + " : "); int count
= 0; for (int j =
0; j < inputString.Length; j++) {
if (inputString[0] == inputString[j])
{
count++;
} }
Console.WriteLine(count);
inputString = inputString.Replace(inputString[0].ToString(), string.Empty); } } |
output
Using LINQ
Group By method to count character occurrences in C#:
private static void
CharactersOccurrence() { Console.Write("Enter
the string : "); string
inputString = Console.ReadLine();
Dictionary<char, int> dict = inputString.Replace("
", string.Empty)
.GroupBy(c => c)
.ToDictionary(gr => gr.Key, gr => gr.Count()); foreach (var
item in dict.Keys) {
Console.WriteLine(item + " : " +
dict[item]); }
} |
Output
EmoticonEmoticon