ProblemYou need to count occurrences of a specific word or substring in a string. SolutionSample code folder: Chapter 05\CountSubstring There are three standard approaches to this problem:
DiscussionThis recipe's sample code presents all three techniques. You can decide, based on your specific programming task, which will work best for you. Here's the setup: Imports System.Text.RegularExpressions ' …Later, in a method… Dim quote As String = "The important thing is not to " & _ "stop questioning. --Albert Einstein" Dim count1 As Integer Dim count2 As Integer Dim count3 As Integer With the first technique, the Regex.Matches() method returns a collection of matches on the searched-for string, and the collection's Count property provides the number we want: count1 = Regex.Matches(quote, "(in)+").Count The second technique splits the string using the searched-for string as the split point. The result of the split is a string array, and its Length is one greater than the number of split points where each substring occurred: count2 = Split(quote, "in").Length - 1 The third technique involves a little more coding, but no string data is shuffled in memory during the search, resulting in an efficient way to locate and count each occurrence of the searched-for string. The IndexOf() method searches for the next occurrence of a string within another, optionally starting the search at an indexed location within the string: Dim content As String = "in" Dim position As Integer = -content.Length Do position = quote.IndexOf(content, position + content.Length) If (position < 0) Then Exit Do count3 += 1 Loop This lets the search proceed from occurrence to occurrence until IndexOf() runs out of matches and returns an index of1. count3 keeps count of the number of times the IndexOf() search is successful, providing a count of the occurrences. The last line of the example code formats and displays the three counts, as shown in Figure 5-31: MsgBox(String.Format( _ "{0}{3}{1}{3}{2}", count1, count2, count3, vbNewLine)) Figure 5-31. The substring "in" occurs four times in the sample string |