I am running a index search on a string in a rich textbox, i have a list of keywords which need to be a different color in this textbox. how do i run a search on a string in vb2005 and get a list of indexes where the text matched my search?
A:
Here is a fairly simple solution. Note that it will find the word "our" in "Four". If that is not desirable you can write something to eliminate overlapping matches.
Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim SearchText As String = "One Two Three Four"
Dim Keywords As String() = {"One", "Four", "our"}
Dim WordMatches As New Generic.List(Of WordMatch)
For Each KeyWord As String In Keywords
Dim i As Int32 = 0
While i <> -1
i = SearchText.IndexOf(KeyWord, i, System.StringComparison.OrdinalIgnoreCase)
If i <> -1 Then
Dim MyMatch As New WordMatch
MyMatch.CharIndex = i
MyMatch.Word = KeyWord
WordMatches.Add(MyMatch)
i += KeyWord.Length
End If
End While
Next
End Sub
Private Structure WordMatch
Public CharIndex As Int32
Public Word As String
End Structure
Carter
2010-07-30 17:08:18
very similar to what i did, it took a very long time to loop through the whole string
Jim
2010-07-31 00:25:13