How to count character count exists in a String C# Examples

This tutorial explains about occurrence of character count in a String in C# with an example

Count of chars occurrence in a String

There are multiple ways to count character occurrences in a String.

The first way, using the String.Split() method.

  • Split function takes character, returns a matched character of an array
  • Finally, return the length of an array.

Here is an example

using System;
                    
public class Program
{
    public static void Main()
    {
        var str= "hello";
        var count=str.Split('l').Length-1;

    Console.WriteLine(count); // 2
    }
}

The second way, with the .NET 7 version, Regex provides easy and performance APIs for character or word

  • First, Split the string, based on character or word, returns an array of substrings of characters
  • Next, Find the length of an array, return and count
var str= "hello";
int count = Regex.Split(str, "l").Length;
Console.WriteLine(count); // 2

The third way, the native way of iterating a string character using an index for loop and checking each character matched with the given character, increment count.

Finally, return the count.

var str= "hello";
int count = 0;
for (int i = 0; i < str.Length; i++)
   if (s[i] == 'l') count++;

Console.WriteLine(count); // 2

The fourth way, the String.IndexOf() function

Iterate using a while loop for a given character and location and increment the counter.

var str= "hello";
int count = 0, n = 0;
while ((n = str.IndexOf('l', n) + 1) != 0) count++;
Console.WriteLine(count); // 2