Counting Character Occurrences in a String in C# Examples

This tutorial explores the counting of character occurrences in a string in C# with various examples.

There are several ways to count character occurrences in a string.

using the String.Split() method.

The first method involves using the String.Split() method:

  • The Split function takes a character and returns an array of matched characters.
  • Finally, the length of the array is returned.

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
    }
}

Using Regex in .NET 7 Version

The second method, available in .NET 7, leverages Regex to provide easy and performance-oriented APIs for character or word counting.

First, split the string based on a character or word, resulting in an array of substrings. Next, find the length of the array and return the count.

var str= "hello";
int count = Regex.Split(str, "l").Length;
Console.WriteLine(count); // 2

Using for loop in C#

The third method involves iterating through the string characters using an index-based for loop, checking each character against the given character, and incrementing the count.

Finally, the count is returned.

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

Console.WriteLine(count); // 2

Using String.IndexOf() Method

The fourth method involves using the String.IndexOf() function:

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

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

These examples provide multiple ways to counting character occurrences in a string in C#.