2010-07-25 102 views
1

我在富文本框中的字符串上運行索引搜索,我有一個關鍵字列表,該列表中的關鍵字在此文本框中需要是不同的顏色。我如何在vb2005中的字符串上運行搜索並獲取文本與我的搜索匹配的索引列表?從vb2005中的文本搜索中獲取索引列表

回答

0

這是一個相當簡單的解決方案。請注意,它會在「四」中找到「我們」這個詞。如果這是不可取的,你可以寫一些東西來消除重疊匹配。

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 
+0

與我所做的非常相似,它花了很長時間來遍歷整個字符串 – Jim 2010-07-31 00:25:13