C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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.
Input and output Input strings: Sam's first name is Sam. Dot Net Perls is about Dot Net No duplicates here aaaa Words: Sam Net here aa Counts: 2 2 1 2
Example. To start, here is an easy method that uses IndexOf and a loop to count up the number of occurrences of a specified string in another string. This method receives two 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.
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; } }
In this example, the counting method (CountStringOccurrences) is a static method. The method does not need to store state. We place it in a static class, a convenient place for helper methods.
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.
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".
An MSDN article shows how to count instances of a word with LINQ, but their approach is likely slow. It is confusing—I would not use it in an important program. The example mostly demonstrates the use of LINQ.
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.