This post will discuss how to count occurrences of a given character in a string in C#.

1. Using Enumerable.Count() method (System.Linq)

The recommended solution is to use LINQ’s Count() method to count occurrences of the given character in a string. This method is demonstrated below:

Download  Run Code

2. Using Enumerable.Where() method (System.Linq)

Here’s another LINQ solution that uses the Where() method to filter the string. The following code example shows how to use this:

Download  Run Code

3. Using String.Split() method

Here, the idea is to split the string with a specified character using the String.Split() method and use the Length property of the resultant string array to determine the count. This is demonstrated below:

Download  Run Code

4. Using foreach loop

We can also write our own logic for this simple task. The idea is to iterate over the characters in the string using a foreach loop and keep a matching character count.

Download  Run Code

5. Using Regex.Matches() method

Regex.Matches() method is used to search for the specified input string for all occurrences of the specified regular expression. We can use it as follows to count occurrences of a character within a string.

Download  Run Code

That’s all about counting occurrences of a character within a string in C#.