Home
C#
String Occurrence Count
Updated Nov 8, 2023
Dot Net Perls
String occurrence count. A substring may occur several times in a string. We can count the number of occurrences of one string in another string.
Method uses. Counting occurrence of strings is useful for validity checks. It can help with checking that only one tag string is found in some HTML.
String IndexOf
while
Example. 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.
Argument 1 The first parameter is the string that contains the data you are checking.
Argument 2 This is the pattern you want to count. So if the string is "cat, frog, cat" and this argument is "cat" we get 2.
Result We can see that the 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
Notes, extensions. 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.
Extension
Tip You could count overlapping occurrences by changing the increment to "i++" instead of "i += pattern.Length".
String 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Nov 8, 2023 (edit).
Home
Changes
© 2007-2025 Sam Allen