Currently I'm using InStr to find a string in a string, I'm new to VB.NET and wondering if I can use InStr to search every element of an array in a string, or a similar function like this:
InStr(string, array)
Thanks.
You need to loop:
Dim bFound As Boolean = False
For Each elem As String In array
If myString.Contains(elem) Then
bFound = True
Exit For
End If
Next
You can transform it into a function to call it more than once easily:
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
Then:
MyInStr("my string text", New String() {"my", "blah", "bleh"})
Dim myVar As Type is completly correct in VB.NET so there is something strange in your platform. Maybe you are talking about javascript?Here goes the LINQ solution:
Dim a() = {"123", "321", "132"}
Dim v = a.Select(Function(x) InStr(x, "3")).ToArray
MessageBox.Show(String.Join(",", v)) '3,1,2
x.IndexOf in VB.NET, rather than the old InStr function.Converting SysDragon's answer to classic asp:
You need to loop:
Dim bFound
bFound = False
For Each elem In myArray
If InStr(myString, elem)>=0 Then
bFound = True
Exit For
End If
Next
You can transform it into a function to call it more than once easily:
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"))
If you are looking at searching for a string in any of the items in a string array, then you can use array.find(<T>) method. See more here: http://msdn.microsoft.com/en-IN/library/d9hy2xwa%28v=vs.90%29.aspx
Instr returns an integer specifying the start position of the first occurrence of one string within another.
Refer this
To find string in a string you can use someother method
Here is an example of highlighting all the text you search for at the same time but if that is not what you want, you have to solve it on your own.
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
This method with search for text "boy" in RichTextBox2, change the textcolor to red and back color to cyan
Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
findTextAndHighlight("boy", RichTextBox2)
End Sub