Find All Occurrences of Specific Text in a String

Problem

You want to count how many times a certain word or sequence of characters occurs in a string.

Solution

Call the String.IndexOf method multiple times in a loop, until you reach the end of the string.

Discussion

The String class provides an IndexOf method that returns the location of the first match in a string. Fortunately, there is an overloaded version of IndexOf that enables you to specify a starting position for the search. By stepping through the string in a loop, specifying greater and greater start positions after each match, you can retrieve a list of all matches. (Another overload enables you to limit the number of characters the search will examine.)

Here’s a function that simply counts ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.