How to: Search for a String in an Array of Strings (Visual Basic)

This example loops over each string in an array of strings to determine which ones contain the specified substring. For each match, the example displays the index of the substring in the string.

Example

The following example uses the Contains and IndexOf methods of the String object.

The Contains method indicates whether the string contains the specified substring.

The IndexOf method reports the location of the first character of the first occurrence of the substring. The index is 0-based, which means the first character of a string has an index of 0. If IndexOf does not find the substring, it returns -1.

Dim StrArray() As String = {"ABCDEFG", "HIJKLMNOP"}
Dim FindThisString As String = "JKL" 
For Each Str As String In StrArray
    If Str.Contains(FindThisString) Then
        MsgBox("Found " & FindThisString & " at index " & _
          Str.IndexOf(FindThisString))
    End If 
Next

This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Data Types - defined by Visual Basic. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).

Compiling the Code

This example requires:

Robust Programming

The IndexOf method is case-sensitive and uses the current culture.

For optimal error control, you might want to enclose the string search in the Try block of a Try...Catch...Finally Statement (Visual Basic) construction.

See Also

Tasks

How to: Search Within a String (Visual Basic)

Reference

Try...Catch...Finally Statement (Visual Basic)

IndexOf

Other Resources

Introduction to Strings in Visual Basic