C# String Occurrence Count (IndexOf, While)

Count the occurrences of a string within another string. Use IndexOf and a while-loop.

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. This is useful for validity checks. It helps with checking that only one tag string is found in your HTML.Strings

To start, here is a method that uses IndexOf and a while-loop to count up the number of occurrences of a specified string in another string. This method receives 2 string parameters.
Note: The first parameter is the string that contains the data you are checking. The second is the pattern you want to count.
CountStringOccurrences: This is a static method. It does not need to store state. We place it in a static class, a convenient place for helper methods.
C# program that counts strings using System; class Program { static void Main() { string s1 = "Sam's first name is Sam."; string s2 = "Dot Net Perls is about Dot Net"; string s3 = "No duplicates here"; string s4 = "aaaa"; Console.WriteLine(TextTool.CountStringOccurrences(s1, "Sam")); // 2 Console.WriteLine(TextTool.CountStringOccurrences(s1, "cool")); // 0 Console.WriteLine(TextTool.CountStringOccurrences(s2, "Dot")); // 2 Console.WriteLine(TextTool.CountStringOccurrences(s2, "Net")); // 2 Console.WriteLine(TextTool.CountStringOccurrences(s3, "here")); // 1 Console.WriteLine(TextTool.CountStringOccurrences(s3, " ")); // 2 Console.WriteLine(TextTool.CountStringOccurrences(s4, "aa")); // 2 } } /// <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; } } Output 2 0 2 2 1 2 2

In the Main method, which we use to test the CountStringOccurrences method, we see that "Sam" occurs twice in the example string. This matches the requirement. It is usually best to simplify the branches in your code.If
Also: It is not an extension method. But you are free to adapt it with the this-keyword.
Tip: You could count overlapping occurrences by changing the increment to "i++" instead of "i += pattern.Length".
String Length

Summary. We saw how to count occurrences of one, smaller string in another, larger string. Importantly, we only loop once over the source, which reduces the cost of the method. I use this method to do simple validation of HTML.

© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.