目前我正在使用InStr在字符串中查找字符串,我是VB.NET的新手,想知道我是否可以使用InStr来搜索字符串中数组的每个元素,或类似的函数:
InStr(string, array)
感谢。
答案 0 :(得分: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"})
答案 1 :(得分:3)
这是LINQ解决方案:
Dim a() = {"123", "321", "132"}
Dim v = a.Select(Function(x) InStr(x, "3")).ToArray
MessageBox.Show(String.Join(",", v)) '3,1,2
答案 2 :(得分:1)
如果您正在寻找在字符串数组中的任何项目中搜索字符串,那么您可以使用array.find(<T>)
方法。点击此处:http://msdn.microsoft.com/en-IN/library/d9hy2xwa%28v=vs.90%29.aspx
答案 3 :(得分: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中搜索文本“boy”,将文本颜色更改为红色,将背景颜色更改为青色
Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
findTextAndHighlight("boy", RichTextBox2)
End Sub
答案 4 :(得分: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
然后:
MyInStr("my string text", Array("my", "blah", "bleh"))