Imports System
Module FindOccurrences
'
' Find all starting indices of a word inside a larger text.
' This function uses String.IndexOf in a loop. The method is efficient
' and implemented in optimized native code, making it ideal for substring search.
'
Sub FindAllOccurrences(text As String, word As String)
If word.Length = 0 Then
Return ' Searching for an empty word is meaningless
End If
Dim index As Integer = text.IndexOf(word) ' First occurrence
While index <> -1
Console.WriteLine(index) ' Print the index
'
' Search again starting one character after the previous match.
' This allows detection of overlapping matches.
'
index = text.IndexOf(word, index + 1)
End While
End Sub
Sub Main()
Dim text As String =
"the quick brown fox jumps over the lazy dog. the fox is clever."
Dim word As String = "the"
Console.WriteLine("Text: " & text)
Console.WriteLine("Word: """ & word & """")
Console.WriteLine()
Console.WriteLine("Occurrences at indices:")
FindAllOccurrences(text, word)
End Sub
End Module
'
' run:
'
' Text: the quick brown fox jumps over the lazy dog. the fox is clever.
' Word: "the"
'
' Occurrences at indices:
' 0
' 31
' 45
'