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

1. Using Regex.Matches() method

The Regex.Matches() method searches a string for all occurrences of a regular expression. The idea is to use it with the Count() method to get the count of all the matches, as shown below:

Download  Run Code

2. Using String.IndexOf() method

The String.indexOf() method returns the index of the first appearance of the given string in a sequence, and returns -1 if the string is not found. It can be used within a while loop to find all occurrences of a substring in a string, as demonstrated below:

Download  Run Code

3. Using Enumerable.Count() method

If you need to count all occurrences of a character within a string, consider using LINQ’s Enumerable.Count() method. This method can be invoked on a string, since a string is simply a collection of characters:

Download  Run Code

 
If you are not allowed to use LINQ, you can split the string using the given character as delimiter:

Download  Run Code

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