O'Reilly logo

Microsoft® Visual Basic® .NET Programmer's Cookbook by Matthew MacDonald

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required