Count occurrences of a substring in a string in C#
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
using System; using System.Text.RegularExpressions; public static class StringExtensions { public static int Count(this string input, string substr) { return Regex.Matches(input, substr).Count; } } public class Example { public static void Main() { string input = "Hello World"; int freq = input.Count("l"); Console.WriteLine(freq); // 3 } } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
using System; public static class StringExtensions { public static int Count(this string input, string substr) { int freq = 0; int index = input.IndexOf(substr); while (index >= 0) { index = input.IndexOf(substr, index + substr.Length); freq++; } return freq; } } public class Example { public static void Main() { string input = "Hello World"; int freq = input.Count("l"); Console.WriteLine(freq); // 3 } } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
using System; using System.Linq; public static class StringExtensions { public static int Count(this string input, char c) { return input.Count(ch => ch == c); } } public class Example { public static void Main() { string input = "Hello World"; int freq = input.Count('l'); Console.WriteLine(freq); // 3 } } |
If you are not allowed to use LINQ, you can split the string using the given character as delimiter:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
using System; public static class StringExtensions { public static int Count(this string input, char c) { return input.Split(c).Length - 1; } } public class Example { public static void Main() { string input = "Hello World"; int freq = input.Count('l'); Console.WriteLine(freq); // 3 } } |
That’s all about counting occurrences of a substring in a string in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)