String
occurrence countA substring may occur several times in a string
. We can count the number of occurrences of one string
in another string
.
Counting occurrence of strings is useful for validity checks. It can help with checking that only one tag string
is found in some HTML.
This method uses IndexOf
and a while
-loop to count up the number of occurrences of a specified string
in another string
. It receives 2 string
parameters.
string
that contains the data you are checking.string
is "cat, frog, cat" and this argument is "cat" we get 2.string
"cat" occurs twice in the input string, while the string
"DOG" occurs zero times.using System; class Program { static void Main() { string value = "cat, frog, cat"; // These should be 2 instances. Console.WriteLine(TextTool.CountStringOccurrences(value, "cat")); // There should be 0 instances. Console.WriteLine(TextTool.CountStringOccurrences(value, "DOG")); } } /// <summary> /// Contains static text methods. /// Put this in a separate class in your project. /// </summary> public static class TextTool { /// <summary> /// Count occurrences of strings. /// </summary> public static int CountStringOccurrences(string text, string pattern) { // Loop through all instances of the string 'text'. int count = 0; int i = 0; while ((i = text.IndexOf(pattern, i)) != -1) { i += pattern.Length; count++; } return count; } }2 0
The code example is not an extension method. But you are free to adapt it with the this
-keyword—place it in a static
class
.
pattern.Length
".We saw how to count occurrences of one, smaller string
in another, larger string
. We only loop once over the source, which reduces the cost of the method.