Como: Procurar por uma sequência de caracteres em uma matriz de sequências de caracteres (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.

Exemplo

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. O índice é-baseada em 0, que significa que o primeiro caractere de uma seqüência tem um índice de 0. Se IndexOf não encontrar a subseqüência de caracteres, ele retornará -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

Este exemplo de código também está disponível como um trecho de código IntelliSense. In the code snippet picker, it is located in Data Types - defined by Visual Basic. For more information, see Como: Inserir trechos de código de IntelliSense.

Compilando o código

This example requires:

Programação robusta

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 Instrução Try...Catch...Finally (Visual Basic) construction.

Consulte também

Tarefas

Como: Pesquisar dentro de uma cadeia de caracteres (Visual Basic)

Referência

Instrução Try...Catch...Finally (Visual Basic)

IndexOf

Outros recursos

Introdução a sequências de caracteres no Visual Basic