2013-04-25 84 views
1

當前我正在使用InStr在字符串中查找字符串,我是VB.NET新手,想知道如果我可以使用InStr來搜索字符串中數組的每個元素,或者類似的功能是這樣的:InStr數組在字符串中

InStr(string, array) 

謝謝。

回答

3

您需要循環:

Dim bFound As Boolean = False 
For Each elem As String In array 
    If myString.Contains(elem) Then 
     bFound = True 
     Exit For 
    End If 
Next 

你可以將其變成一個函數,以便多次調用它:

Public Function MyInStr(myString As String, array() As String) As Boolean 
    For Each elem As String In array 
     If myString.Contains(elem) Then return True 
    Next 

    return false 
End Function 

然後:

MyInStr("my string text", New String() {"my", "blah", "bleh"}) 
+0

我得到錯誤在Dim bFound As Bollean = False – XandrUu 2013-04-25 11:38:30

+0

@XandrUu你有一個錯字there.should布爾 – Constanta 2013-04-25 11:41:05

+0

這是代碼:昏暗accesFile作爲布爾和錯誤在作爲 – XandrUu 2013-04-25 11:44:45

0

Instr返回一個整數,指定一個字符串中第一次出現的位置。

參考this

要在字符串中找到字符串就可以使用一些其它方法

這裏是突出你在同一時間搜索文本的一個例子,但如果這是不是你想要的,你必須自己解決它。

Sub findTextAndHighlight(ByVal searchtext As String, ByVal rtb As RichTextBox) 
Dim textEnd As Integer = rtb.TextLength 
Dim index As Integer = 0 
Dim fnt As Font = New Font(rtb.Font, FontStyle.Bold) 
Dim lastIndex As Integer = rtb.Text.LastIndexOf(searchtext) 
While (index < lastIndex) 
    rtb.Find(searchtext, index, textEnd, RichTextBoxFinds.WholeWord) 
    rtb.SelectionFont = fnt 
    rtb.SelectionLength = searchtext.Length 
    rtb.SelectionColor = Color.Red 
    rtb.SelectionBackColor = Color.Cyan 
    index = rtb.Text.IndexOf(searchtext, index) + 1 
End While 
End Sub 

這種方法與搜索文字「男孩」在RichTextBox2的文本顏色變爲紅色和背部顏色爲青色

Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click 
findTextAndHighlight("boy", RichTextBox2) 
End Sub 
+0

它的更好,如果你可以在你的答案包括直接的例子和信息。除此之外,提供一個鏈接是很好的,但如果鏈接是唯一的答案,如果鏈接被破壞,你的答案將對未來的訪問者無用。 – 2013-04-25 11:51:34

+1

@Steven Doggart,謝謝你的有用建議。我會更新我的答案 – 2013-04-25 11:52:34

0

轉換SysDragon的回答讓傳統的ASP:

您需要循環:

Dim bFound 
bFound = False 

For Each elem In myArray 
    If InStr(myString, elem)>=0 Then 
     bFound = True 
     Exit For 
    End If 
Next 

你可以將它變成一個函數來調用它不止一次容易:

Function MyInStr(myString, myArray) 
    Dim bFound 
    bFound = false 

    For Each elem In myArray 
     If InStr(myString, elem)>=0 Then 
      bFound = True 
      Exit For 
     End If 
    Next 

    MyInStr = bFound 
End Function 

Then:

MyInStr("my string text", Array("my", "blah", "bleh")) 
2

這裏去的LINQ解決方案:

Dim a() = {"123", "321", "132"} 
Dim v = a.Select(Function(x) InStr(x, "3")).ToArray 
MessageBox.Show(String.Join(",", v)) '3,1,2 
+1

我建議在VB.NET中使用'x.IndexOf',而不是舊的'InStr'函數。 – 2013-04-25 12:07:35

+0

@StevenDoggart:好想法。幸運的是,上面的代碼支持自定義,所以OP可以在那裏使用任何函數。 – Neolisk 2013-04-25 12:08:52