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
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.
static void Main()
string value = "cat, frog, cat";
// These should be 2 instances.
// There should be 0 instances.
/// Contains static text methods.
/// Put this in a separate class in your project.
public static class TextTool
/// Count occurrences of strings.
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;
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.