Home
Map
String Occurrence CountCount the occurrences of a string within another string. Use IndexOf and a while-loop.
C#
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.
IndexOf
While
Required input, output. Consider a string that contains the word "cat" in 2 places. By counting the occurrences of "cat," we should receive the value 2.
INPUT: cat, frog, cat OUTPUT: 2
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.
Detail The first parameter is the string that contains the data you are checking. The second is the pattern you want to count.
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
A summary. 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.
C#VB.NETPythonGolangJavaSwiftRust
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.
No updates found for this page.
Home
Changes
© 2007-2023 Sam Allen.