Home
C#
String Occurrence Count
This page was last reviewed on 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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 8, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.