String.Split Método

Definição

Retorna uma matriz de cadeia de caracteres que contém as subcadeias de caracteres nesta instância delimitadas por elementos de uma cadeia de caracteres especificada ou da matriz de caracteres Unicode.

Sobrecargas

Split(Char[])

Divide uma cadeia de caracteres em substrings baseadas nos caracteres delimitadores especificados.

Split(Char, StringSplitOptions)

Divide uma cadeia de caracteres em substrings baseadas em um caractere delimitador especificado e, opcionalmente, em opções.

Split(Char[], Int32)

Divide uma cadeia de caracteres em um número máximo de substrings baseadas nos caracteres delimitadores especificados.

Split(Char[], StringSplitOptions)

Divide uma cadeia de caracteres em substrings baseadas em caracteres delimitadores e opções.

Split(String, StringSplitOptions)

Divide uma cadeia de caracteres em substrings com base no separador de cadeias de caracteres fornecido.

Split(String[], StringSplitOptions)

Divide uma cadeia de caracteres em substrings baseadas em uma cadeia de caracteres delimitadora especificada e, opcionalmente, em opções.

Split(Char, Int32, StringSplitOptions)

Divide uma cadeia de caracteres em um número máximo de substrings baseadas em um caractere delimitador especificado e, opcionalmente, em opções. Divide uma cadeia de caracteres em um número máximo de substrings baseadas no separador de caracteres fornecido, omitindo opcionalmente substrings vazias do resultado.

Split(Char[], Int32, StringSplitOptions)

Divide uma cadeia de caracteres em um número máximo de substrings baseadas em caracteres delimitadores especificados e, opcionalmente, em opções.

Split(String, Int32, StringSplitOptions)

Divide uma cadeia de caracteres em um número máximo de substrings baseadas em uma cadeia de caracteres delimitadora especificada e, opcionalmente, em opções.

Split(String[], Int32, StringSplitOptions)

Divide uma cadeia de caracteres em um número máximo de substrings baseadas em cadeias de caracteres delimitadoras especificadas e, opcionalmente, em opções.

Comentários

Split é usado para dividir uma cadeia de caracteres delimitada em subcadeias de caracteres. Você pode usar uma matriz de caracteres ou uma matriz de cadeia de caracteres para especificar zero ou mais caracteres delimitadores ou cadeias de caracteres. Se nenhum caractere delimitador for especificado, a cadeia de caracteres será dividida em caracteres de espaço em branco.

As sobrecargas do Split método permitem limitar o número de subcadeias de caracteres retornadas pelo método (o Split(Char[], Int32) método ), para especificar se devem ser incluídas cadeias de caracteres vazias e/ou subcadeias de caracteres no resultado (os Split(Char[], StringSplitOptions) métodos e Split(String[], StringSplitOptions) ) ou para fazer ambos (os Split(Char[], Int32, StringSplitOptions) métodos e Split(String[], Int32, StringSplitOptions) ).

Dica

O Split método nem sempre é a melhor maneira de dividir uma cadeia de caracteres delimitada em subcadeias de caracteres. Se você não quiser extrair todas as subcadeias de caracteres de uma cadeia de caracteres delimitada ou se quiser analisar uma cadeia de caracteres com base em um padrão em vez de um conjunto de caracteres delimitadores, considere o uso de expressões regulares ou combine um dos métodos de pesquisa que retorna o índice de um caractere com o Substring método . Para obter mais informações, consulte Extrair subcadeias de caracteres de uma cadeia de caracteres.

Exemplo

Os exemplos a seguir mostram três sobrecargas diferentes de String.Split(). O primeiro exemplo chama a Split(Char[]) sobrecarga e passa em um único delimitador.

string s = "You win some. You lose some.";

string[] subs = s.Split(' ');

foreach (var sub in subs)
{
    Console.WriteLine($"Substring: {sub}");
}

// This example produces the following output:
//
// Substring: You
// Substring: win
// Substring: some.
// Substring: You
// Substring: lose
// Substring: some.
let s = "You win some. You lose some."

let subs = s.Split ' '

for sub in subs do
    printfn $"Substring: {sub}"

// This example produces the following output:
//
// Substring: You
// Substring: win
// Substring: some.
// Substring: You
// Substring: lose
// Substring: some.
Dim s As String = "You win some. You lose some."
Dim subs As String() = s.Split()

For Each substring As String In subs
    Console.WriteLine($"Substring: {substring}")
Next

' This example produces the following output:
'
' Substring: You
' Substring: win
' Substring: some.
' Substring: You
' Substring: lose
' Substring: some.

Os caracteres de ponto (.) estão incluídos em duas das substrings. Para excluir caracteres de ponto, adicione-os como caracteres delimitadores adicionais. O próximo exemplo mostra como fazer isso.

string s = "You win some. You lose some.";

string[] subs = s.Split(' ', '.');

foreach (var sub in subs)
{
    Console.WriteLine($"Substring: {sub}");
}

// This example produces the following output:
//
// Substring: You
// Substring: win
// Substring: some
// Substring:
// Substring: You
// Substring: lose
// Substring: some
// Substring:
let s = "You win some. You lose some."

let subs = s.Split(' ', '.')

for sub in subs do
    printfn $"Substring: {sub}"

// This example produces the following output:
//
// Substring: You
// Substring: win
// Substring: some
// Substring:
// Substring: You
// Substring: lose
// Substring: some
// Substring:
Dim s As String = "You win some. You lose some."
Dim subs As String() = s.Split(" "c, "."c)

For Each substring As String In subs
    Console.WriteLine($"Substring: {substring}")
Next

' This example produces the following output:
'
' Substring: You
' Substring: win
' Substring: some
' Substring:
' Substring: You
' Substring: lose
' Substring: some
' Substring:

Os pontos sumiram das substrings, mas duas substrings vazias extras foram incluídas agora. Essas subcadeias de caracteres vazias representam a subcadeia de caracteres entre uma palavra e o período que a segue. Para omitir substrings vazias da matriz resultante, é possível chamar a sobrecarga Split(Char[], StringSplitOptions) e especificar StringSplitOptions.RemoveEmptyEntries para o parâmetro options.

string s = "You win some. You lose some.";
char[] separators = new char[] { ' ', '.' };

string[] subs = s.Split(separators, StringSplitOptions.RemoveEmptyEntries);

foreach (var sub in subs)
{
    Console.WriteLine($"Substring: {sub}");
}

// This example produces the following output:
//
// Substring: You
// Substring: win
// Substring: some
// Substring: You
// Substring: lose
// Substring: some
let s = "You win some. You lose some."
let separators = [| ' '; '.' |]

let subs = s.Split(separators, StringSplitOptions.RemoveEmptyEntries)

for sub in subs do
    printfn $"Substring: {sub}"

// This example produces the following output:
//
// Substring: You
// Substring: win
// Substring: some
// Substring: You
// Substring: lose
// Substring: some
Dim s As String = "You win some. You lose some."
Dim separators As Char() = New Char() {" "c, "."c}
Dim subs As String() = s.Split(separators, StringSplitOptions.RemoveEmptyEntries)

For Each substring As String In subs
    Console.WriteLine($"Substring: {substring}")
Next

' This example produces the following output:
'
' Substring: You
' Substring: win
' Substring: some
' Substring: You
' Substring: lose
' Substring: some

As seções para as sobrecargas individuais de String.Split() contêm outros exemplos.

Split(Char[])

Divide uma cadeia de caracteres em substrings baseadas nos caracteres delimitadores especificados.

public:
 cli::array <System::String ^> ^ Split(... cli::array <char> ^ separator);
public string[] Split (params char[] separator);
public string[] Split (params char[]? separator);
member this.Split : char[] -> string[]
Public Function Split (ParamArray separator As Char()) As String()

Parâmetros

separator
Char[]

Uma matriz de caracteres delimitadores, uma matriz vazia que não contém nenhum delimitador ou null.

Retornos

String[]

Uma matriz cujos elementos contêm as subcadeias de caracteres desta instância que são delimitadas por um ou mais caracteres em separator. Para obter mais informações, consulte a seção Comentários.

Exemplos

O exemplo a seguir demonstra como extrair palavras individuais de um bloco de texto tratando o caractere de espaço ( ) e o caractere de guia (\t) como delimitadores. A cadeia de caracteres que está sendo dividida inclui ambos os caracteres.

string s = "Today\tI'm going to school";
string[] subs = s.Split(' ', '\t');

foreach (var sub in subs)
{
    Console.WriteLine($"Substring: {sub}");
}

// This example produces the following output:
//
// Substring: Today
// Substring: I'm
// Substring: going
// Substring: to
// Substring: school
let s = "Today\tI'm going to school"
let subs = s.Split(' ', '\t')

for sub in subs do
    printfn $"Substring: {sub}"

// This example produces the following output:
//
// Substring: Today
// Substring: I'm
// Substring: going
// Substring: to
// Substring: school
Dim s As String = "Today" & vbTab & "I'm going to school"
Dim subs As String() = s.Split(" "c, Char.Parse(vbTab))

For Each substring In subs
    Console.WriteLine("Substring: " & substring)
Next

' This example produces the following output:
'
' Substring: Today
' Substring: I 'm
' Substring: going
' Substring: to
' Substring: school

Comentários

Quando uma cadeia de caracteres é delimitada por um conjunto conhecido de caracteres, você pode usar o Split(Char[]) método para separá-la em subcadeias de caracteres.

Os caracteres delimitadores não estão incluídos nos elementos da matriz retornada. Por exemplo, se a matriz separadora incluir o caractere "-" e o valor da instância de cadeia de caracteres atual for "aa-bb-cc", o método retornará uma matriz que contém três elementos: "aa", "bb" e "cc".

Se essa instância não contiver nenhum dos caracteres no separator, a matriz retornada consistirá em um único elemento que contém essa instância.

Cada elemento de separator define um caractere delimitador à parte. Se dois delimitadores forem adjacentes ou um delimitador for encontrado no início ou no final dessa instância, o elemento correspondente na matriz retornada conterá Empty.

A tabela a seguir mostra alguns exemplos.

Linguagem Valor da cadeia de caracteres Separador Matriz retornada
C# "42, 12, 19" new Char[] {',', ' '} {"42", "", "12", "", "19"}
Visual Basic "42, 12, 19" Char() = {","c, " "c}) {"42", "", "12", "", "19"}
C# "42..12..19." new Char[] {'.'} {"42", "", "12", "", "19", ""}
Visual Basic "42..12..19." Char() = {". c} {"42", "", "12", "", "19", ""}
C# "Banana" new Char[] {'.'} {"Banana"}
Visual Basic "Banana" Char() = {". c} {"Banana"}
C# "Darb\nSmarba" new Char[] {} {"Darb", "Smarba"}
Visual Basic "Darb" & vbLf & "Smarba" Char() = {} {"Darb", "Smarba"}
C# "Darb\nSmarba" null {"Darb", "Smarba"}
Visual Basic "Darb" & vbLf & "Smarba" Nothing {"Darb", "Smarba"}

A matriz separadora

Cada elemento do separador define um delimitador separado que consiste em um único caractere.

Se o separator argumento for null ou não contiver caracteres, o método tratará caracteres de espaço em branco como delimitadores. Os caracteres de espaço em branco são definidos pelo padrão Unicode e o Char.IsWhiteSpace método retorna true se um caractere de espaço em branco é passado para ele.

String.Split(Char[]) e resolução de sobrecarga do compilador

Embora o parâmetro único para essa sobrecarga de seja uma matriz de String.Split caracteres, você pode chamá-lo com um único caractere, como mostra o exemplo a seguir.

string value = "This is a short string.";
char delimiter = 's';
string[] substrings = value.Split(delimiter);
foreach (var substring in substrings)
    Console.WriteLine(substring);

// The example displays the following output:
//     Thi
//      i
//      a
//     hort
//     tring.
let value = "This is a short string."
let delimiter = 's'
let substrings = value.Split delimiter
for substring in substrings do
    printfn $"{substring}"

// The example displays the following output:
//     Thi
//      i
//      a
//     hort
//     tring.
    Dim value As String = "This is a short string."
    Dim delimiter As Char = "s"c
    Dim substrings() As String = value.Split(delimiter)
    For Each substring In substrings
        Console.WriteLine(substring)
    Next
End Sub

' The example displays the following output:
'
'     Thi
'      i
'      a
'     hort
'     tring.

Como o separator parâmetro é decorado com o ParamArrayAttribute atributo , os compiladores interpretarão um único caractere como uma matriz de caracteres de elemento único. Esse não é o caso de outras String.Split sobrecargas que incluem um separator parâmetro; você deve passar explicitamente essas sobrecargas de uma matriz de caracteres como o separator argumento .

Detalhes da comparação

O Split(Char[]) método extrai as subcadeias de caracteres nessa cadeia de caracteres delimitadas por um ou mais caracteres na separator matriz e retorna essas subcadeias de caracteres como elementos de uma matriz.

O Split(Char[]) método procura delimitadores executando comparações usando regras de classificação ordinal que diferenciam maiúsculas de minúsculas. Para obter mais informações sobre as classificações de palavra, cadeia de caracteres e ordinal, consulte a System.Globalization.CompareOptions enumeração .

Considerações sobre o desempenho

Os métodos Split alocam memória para o objeto de matriz retornado e um objeto String para cada elemento da matriz. Se o aplicativo exigir um desempenho ideal ou se o gerenciamento da alocação de memória for fundamental em seu aplicativo, considere usar o IndexOf método ou IndexOfAny . Você também tem a opção de usar o Compare método para localizar uma subcadeia de caracteres dentro de uma cadeia de caracteres.

Para dividir uma cadeia de caracteres em um caractere separador, use o IndexOf método ou IndexOfAny para localizar um caractere separador na cadeia de caracteres. Para dividir uma cadeia de caracteres em uma cadeia de caracteres separadora, use o IndexOf método ou IndexOfAny para localizar o primeiro caractere da cadeia de caracteres separadora. Em seguida, use o método Compare para determinar se os caracteres depois desse primeiro caractere são iguais aos caracteres restantes da cadeia de caracteres separadora.

Além disso, caso o mesmo conjunto de caracteres seja usado para dividir cadeias de caracteres em várias chamadas de método Split, considere criar uma matriz única e referencie-a em cada chamada de método. Isso reduz significativamente a sobrecarga adicional de cada chamada de método.

Notas aos Chamadores

No .NET Framework 3.5 e versões anteriores, se o Split(Char[]) método for passado um separator que seja null ou não contenha caracteres, o método usará um conjunto ligeiramente diferente de caracteres de espaço em branco para dividir a cadeia de caracteres do que o Trim(Char[]) método faz para cortar a cadeia de caracteres. Começando com .NET Framework 4, ambos os métodos usam um conjunto idêntico de caracteres de espaço em branco Unicode.

Confira também

Aplica-se a

Split(Char, StringSplitOptions)

Divide uma cadeia de caracteres em substrings baseadas em um caractere delimitador especificado e, opcionalmente, em opções.

public string[] Split (char separator, StringSplitOptions options = System.StringSplitOptions.None);
member this.Split : char * StringSplitOptions -> string[]
Public Function Split (separator As Char, Optional options As StringSplitOptions = System.StringSplitOptions.None) As String()

Parâmetros

separator
Char

Um caractere que delimita as substrings nesta cadeia de caracteres.

options
StringSplitOptions

Uma combinação bit a bit dos valores de enumeração que especifica se substrings devem ser cortadas e se substrings vazias devem ser incluídas.

Retornos

String[]

Uma matriz cujos elementos contêm as subcadeias de caracteres desta instância que são delimitadas por separator.

Aplica-se a

Split(Char[], Int32)

Divide uma cadeia de caracteres em um número máximo de substrings baseadas nos caracteres delimitadores especificados.

public:
 cli::array <System::String ^> ^ Split(cli::array <char> ^ separator, int count);
public string[] Split (char[] separator, int count);
public string[] Split (char[]? separator, int count);
member this.Split : char[] * int -> string[]
Public Function Split (separator As Char(), count As Integer) As String()

Parâmetros

separator
Char[]

Uma matriz de caracteres que delimitam as substrings nesta cadeia de caracteres, uma matriz vazia que não contém delimitadores ou null.

count
Int32

O número máximo de subcadeias de caracteres a serem retornadas.

Retornos

String[]

Uma matriz cujos elementos contêm as subcadeias de caracteres desta instância que são delimitadas por um ou mais caracteres em separator. Para obter mais informações, consulte a seção Comentários.

Exceções

count é negativo.

Exemplos

O exemplo a seguir demonstra como count pode ser usado para limitar o número de cadeias de caracteres retornadas por Split.

string name = "Alex Johnson III";

string[] subs = name.Split(null, 2);

string firstName = subs[0];
string lastName;
if (subs.Length > 1)
{
    lastName = subs[1];
}

// firstName = "Alex"
// lastName = "Johnson III"
let name = "Alex Johnson III"

let subs = name.Split(null, 2)

let firstName = subs[0]
let lastName =
    if subs.Length > 1 then
        subs[1]
    else
        ""

// firstName = "Alex"
// lastName = "Johnson III"
Console.WriteLine("What is your name?")
Dim name As String = Console.ReadLine()

Dim substrings = name.Split(Nothing, 2)
Dim firstName As String = substrings(0)
Dim lastName As String

If substrings.Length > 1 Then
    lastName = substrings(1)
End If

' If the user enters "Alex Johnson III":
' firstName = "Alex"
' lastName = "Johnson III"

Comentários

Os caracteres delimitadores não estão incluídos nos elementos da matriz retornada.

Se essa instância não contiver nenhum dos caracteres no separator, a matriz retornada consistirá em um único elemento que contém essa instância. Se count for zero, uma matriz vazia será retornada.

Caso o parâmetro separator seja null ou não contenha nenhum caractere, os caracteres de espaço em branco devem ser considerados os delimitadores. Os caracteres de espaço em branco são definidos pelo padrão Unicode e o Char.IsWhiteSpace método retorna true se eles são passados para ele.

Cada elemento de separator define um caractere delimitador à parte. Se dois delimitadores forem adjacentes ou um delimitador for encontrado no início ou no final dessa instância, o elemento de matriz correspondente conterá Empty.

Se houver mais de count subcadeias de caracteres nessa instância, as primeiras count - 1 subcadeias de caracteres serão retornadas nos primeiros count - 1 elementos do valor retornado e os caracteres restantes nesta instância serão retornados no último elemento do valor retornado.

Se count for maior que o número de subcadeias de caracteres, as subcadeias de caracteres disponíveis serão retornadas e nenhuma exceção será gerada.

A tabela a seguir mostra alguns exemplos.

Linguagem Valor da cadeia de caracteres Separador Matriz retornada
C# "42, 12, 19" new Char[] {',', ' '} {"42", "", "12", "", "19"}
Visual Basic "42, 12, 19" Char() = {","c, " "c}) {"42", "", "12", "", "19"}
C# "42..12..19." new Char[] {'.'} {"42", "", "12", "", "19", ""}
Visual Basic "42..12..19." Char() = {". c} {"42", "", "12", "", "19", ""}
C# "Banana" new Char[] {'.'} {"Banana"}
Visual Basic "Banana" Char() = {". c} {"Banana"}
C# "Darb\nSmarba" new Char[] {} {"Darb", "Smarba"}
Visual Basic "Darb" & vbLf & "Smarba" Char() = {} {"Darb", "Smarba"}
C# "Darb\nSmarba" null {"Darb", "Smarba"}
Visual Basic "Darb" & vbLf & "Smarba" Nothing {"Darb", "Smarba"}

Considerações sobre o desempenho

Os métodos Split alocam memória para o objeto de matriz retornado e um objeto String para cada elemento da matriz. Caso o aplicativo exija desempenho ideal ou em caso de gerenciamento da alocação da memória ser importante no aplicativo, considere o uso do método IndexOf ou IndexOfAny, e opcionalmente o método de Compare para localizar uma subcadeia de caracteres dentro de uma cadeia de caracteres.

Caso você esteja dividindo uma cadeia de caracteres em um separador de caractere, use o método IndexOf ou IndexOfAny para localizar um caractere separador na cadeia de caracteres. Caso você esteja dividindo uma cadeia de caracteres em uma cadeia de caracteres separadora, use o método IndexOf ou de IndexOfAny para localizar o primeiro caractere da cadeia de caracteres separadora. Em seguida, use o método Compare para determinar se os caracteres depois desse primeiro caractere são iguais aos caracteres restantes da cadeia de caracteres separadora.

Além disso, caso o mesmo conjunto de caracteres seja usado para dividir cadeias de caracteres em várias chamadas de método Split, considere criar uma matriz única e referencie-a em cada chamada de método. Isso reduz significativamente a sobrecarga adicional de cada chamada de método.

Notas aos Chamadores

No .NET Framework 3.5 e versões anteriores, se o Split(Char[]) método for passado um separator que seja null ou não contenha caracteres, o método usará um conjunto ligeiramente diferente de caracteres de espaço em branco para dividir a cadeia de caracteres do que o Trim(Char[]) método faz para cortar a cadeia de caracteres. Começando com .NET Framework 4, ambos os métodos usam um conjunto idêntico de caracteres de espaço em branco Unicode.

Confira também

Aplica-se a

Split(Char[], StringSplitOptions)

Divide uma cadeia de caracteres em substrings baseadas em caracteres delimitadores e opções.

public:
 cli::array <System::String ^> ^ Split(cli::array <char> ^ separator, StringSplitOptions options);
public string[] Split (char[] separator, StringSplitOptions options);
public string[] Split (char[]? separator, StringSplitOptions options);
[System.Runtime.InteropServices.ComVisible(false)]
public string[] Split (char[] separator, StringSplitOptions options);
member this.Split : char[] * StringSplitOptions -> string[]
[<System.Runtime.InteropServices.ComVisible(false)>]
member this.Split : char[] * StringSplitOptions -> string[]
Public Function Split (separator As Char(), options As StringSplitOptions) As String()

Parâmetros

separator
Char[]

Uma matriz de caracteres que delimitam as substrings nesta cadeia de caracteres, uma matriz vazia que não contém delimitadores ou null.

options
StringSplitOptions

Uma combinação bit a bit dos valores de enumeração que especifica se substrings devem ser cortadas e se substrings vazias devem ser incluídas.

Retornos

String[]

Uma matriz cujos elementos contêm as subcadeias de caracteres desta cadeia de caracteres que são delimitadas por um ou mais caracteres em separator. Para obter mais informações, consulte a seção Comentários.

Atributos

Exceções

options não é um dos valores StringSplitOptions.

Exemplos

O exemplo a seguir usa a StringSplitOptions enumeração para incluir ou excluir subcadeias de caracteres geradas pelo Split método .

// This example demonstrates the String.Split(Char[], Boolean) and 
//                               String.Split(Char[], Int32, Boolean) methods
using namespace System;
void Show( array<String^>^entries )
{
   Console::WriteLine( "The return value contains these {0} elements:", entries->Length );
   System::Collections::IEnumerator^ myEnum = entries->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      String^ entry = safe_cast<String^>(myEnum->Current);
      Console::Write( "<{0}>", entry );
   }

   Console::Write( "{0}{0}", Environment::NewLine );
}

int main()
{
   String^ s = ",one,,,two,,,,,three,,";
   array<Char>^sep = gcnew array<Char>{
      ','
   };
   array<String^>^result;
   
   //
   Console::WriteLine( "The original string is \"{0}\".", s );
   Console::WriteLine( "The separation character is '{0}'.", sep[ 0 ] );
   Console::WriteLine();
   
   //
   Console::WriteLine( "Split the string and return all elements:" );
   result = s->Split( sep, StringSplitOptions::None );
   Show( result );
   
   //
   Console::WriteLine( "Split the string and return all non-empty elements:" );
   result = s->Split( sep, StringSplitOptions::RemoveEmptyEntries );
   Show( result );
   
   //
   Console::WriteLine( "Split the string and return 2 elements:" );
   result = s->Split( sep, 2, StringSplitOptions::None );
   Show( result );
   
   //
   Console::WriteLine( "Split the string and return 2 non-empty elements:" );
   result = s->Split( sep, 2, StringSplitOptions::RemoveEmptyEntries );
   Show( result );
}

/*
This example produces the following results:

The original string is ",one,,,two,,,,,three,,".
The separation character is ','.

Split the string and return all elements:
The return value contains these 12 elements:
<><one><><><two><><><><><three><><>

Split the string and return all non-empty elements:
The return value contains these 3 elements:
<one><two><three>

Split the string and return 2 elements:
The return value contains these 2 elements:
<><one,,,two,,,,,three,,>

Split the string and return 2 non-empty elements:
The return value contains these 2 elements:
<one><,,two,,,,,three,,>

*/
// This example demonstrates the String.Split() methods that use
// the StringSplitOptions enumeration.
string s1 = ",ONE,,TWO,,,THREE,,";
string s2 = "[stop]" +
            "ONE[stop][stop]" +
            "TWO[stop][stop][stop]" +
            "THREE[stop][stop]";
char[] charSeparators = new char[] { ',' };
string[] stringSeparators = new string[] { "[stop]" };
string[] result;
// ------------------------------------------------------------------------------
// Split a string delimited by characters.
// ------------------------------------------------------------------------------
Console.WriteLine("1) Split a string delimited by characters:\n");

// Display the original string and delimiter characters.
Console.WriteLine($"1a) The original string is \"{s1}\".");
Console.WriteLine($"The delimiter character is '{charSeparators[0]}'.\n");

// Split a string delimited by characters and return all elements.
Console.WriteLine("1b) Split a string delimited by characters and " +
                  "return all elements:");
result = s1.Split(charSeparators, StringSplitOptions.None);
Show(result);

// Split a string delimited by characters and return all non-empty elements.
Console.WriteLine("1c) Split a string delimited by characters and " +
                  "return all non-empty elements:");
result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);
Show(result);

// Split the original string into the string and empty string before the
// delimiter and the remainder of the original string after the delimiter.
Console.WriteLine("1d) Split a string delimited by characters and " +
                  "return 2 elements:");
result = s1.Split(charSeparators, 2, StringSplitOptions.None);
Show(result);

// Split the original string into the string after the delimiter and the
// remainder of the original string after the delimiter.
Console.WriteLine("1e) Split a string delimited by characters and " +
                  "return 2 non-empty elements:");
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries);
Show(result);

// ------------------------------------------------------------------------------
// Split a string delimited by another string.
// ------------------------------------------------------------------------------
Console.WriteLine("2) Split a string delimited by another string:\n");

// Display the original string and delimiter string.
Console.WriteLine($"2a) The original string is \"{s2}\".");
Console.WriteLine($"The delimiter string is \"{stringSeparators[0]}\".\n");

// Split a string delimited by another string and return all elements.
Console.WriteLine("2b) Split a string delimited by another string and " +
                  "return all elements:");
result = s2.Split(stringSeparators, StringSplitOptions.None);
Show(result);

// Split the original string at the delimiter and return all non-empty elements.
Console.WriteLine("2c) Split a string delimited by another string and " +
                  "return all non-empty elements:");
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);
Show(result);

// Split the original string into the empty string before the
// delimiter and the remainder of the original string after the delimiter.
Console.WriteLine("2d) Split a string delimited by another string and " +
                  "return 2 elements:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.None);
Show(result);

// Split the original string into the string after the delimiter and the
// remainder of the original string after the delimiter.
Console.WriteLine("2e) Split a string delimited by another string and " +
                  "return 2 non-empty elements:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries);
Show(result);

// Display the array of separated strings using a local function
void Show(string[] entries)
{
    Console.WriteLine($"The return value contains these {entries.Length} elements:");
    foreach (string entry in entries)
    {
        Console.Write($"<{entry}>");
    }
    Console.Write("\n\n");
}

/*
This example produces the following results:

1) Split a string delimited by characters:

1a) The original string is ",ONE,,TWO,,,THREE,,".
The delimiter character is ','.

1b) Split a string delimited by characters and return all elements:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>

1c) Split a string delimited by characters and return all non-empty elements:
The return value contains these 3 elements:
<ONE><TWO><THREE>

1d) Split a string delimited by characters and return 2 elements:
The return value contains these 2 elements:
<><ONE,,TWO,,,THREE,,>

1e) Split a string delimited by characters and return 2 non-empty elements:
The return value contains these 2 elements:
<ONE><TWO,,,THREE,,>

2) Split a string delimited by another string:

2a) The original string is "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".
The delimiter string is "[stop]".

2b) Split a string delimited by another string and return all elements:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>

2c) Split a string delimited by another string and return all non-empty elements:
The return value contains these 3 elements:
<ONE><TWO><THREE>

2d) Split a string delimited by another string and return 2 elements:
The return value contains these 2 elements:
<><ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]>

2e) Split a string delimited by another string and return 2 non-empty elements:
The return value contains these 2 elements:
<ONE><TWO[stop][stop][stop]THREE[stop][stop]>

*/
// This example demonstrates the String.Split() methods that use
// the StringSplitOptions enumeration.
 
// Display the array of separated strings using a local function
let show  (entries: string[]) =
    printfn $"The return value contains these {entries.Length} elements:"
    for entry in entries do
        printf $"<{entry}>"
    printf "\n\n"

let s1 = ",ONE,,TWO,,,THREE,,"
let s2 = "[stop]" +
         "ONE[stop][stop]" +
         "TWO[stop][stop][stop]" +
         "THREE[stop][stop]"
let charSeparators = [| ',' |]
let stringSeparators = [| "[stop]" |]
// ------------------------------------------------------------------------------
// Split a string delimited by characters.
// ------------------------------------------------------------------------------
printfn "1) Split a string delimited by characters:\n"

// Display the original string and delimiter characters.
printfn $"1a) The original string is \"{s1}\"."
printfn $"The delimiter character is '{charSeparators[0]}'.\n"

// Split a string delimited by characters and return all elements.
printfn "1b) Split a string delimited by characters and return all elements:"
let result = s1.Split(charSeparators, StringSplitOptions.None)
show result

// Split a string delimited by characters and return all non-empty elements.
printfn "1c) Split a string delimited by characters and return all non-empty elements:"
let result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries)
show result

// Split the original string into the string and empty string before the
// delimiter and the remainder of the original string after the delimiter.
printfn "1d) Split a string delimited by characters and return 2 elements:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.None)
show result

// Split the original string into the string after the delimiter and the
// remainder of the original string after the delimiter.
printfn "1e) Split a string delimited by characters and return 2 non-empty elements:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
show result

// ------------------------------------------------------------------------------
// Split a string delimited by another string.
// ------------------------------------------------------------------------------
printfn "2) Split a string delimited by another string:\n"

// Display the original string and delimiter string.
printfn $"2a) The original string is \"{s2}\"."
printfn $"The delimiter string is \"{stringSeparators[0]}\".\n"

// Split a string delimited by another string and return all elements.
printfn "2b) Split a string delimited by another string and return all elements:"
let result = s2.Split(stringSeparators, StringSplitOptions.None)
show result

// Split the original string at the delimiter and return all non-empty elements.
printfn "2c) Split a string delimited by another string and return all non-empty elements:"
let result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)
show result

// Split the original string into the empty string before the
// delimiter and the remainder of the original string after the delimiter.
printfn "2d) Split a string delimited by another string and return 2 elements:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.None)
show result

// Split the original string into the string after the delimiter and the
// remainder of the original string after the delimiter.
printfn "2e) Split a string delimited by another string and return 2 non-empty elements:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
show result

(*
This example produces the following results:

1) Split a string delimited by characters:

1a) The original string is ",ONE,,TWO,,,THREE,,".
The delimiter character is ','.

1b) Split a string delimited by characters and return all elements:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>

1c) Split a string delimited by characters and return all non-empty elements:
The return value contains these 3 elements:
<ONE><TWO><THREE>

1d) Split a string delimited by characters and return 2 elements:
The return value contains these 2 elements:
<><ONE,,TWO,,,THREE,,>

1e) Split a string delimited by characters and return 2 non-empty elements:
The return value contains these 2 elements:
<ONE><TWO,,,THREE,,>

2) Split a string delimited by another string:

2a) The original string is "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".
The delimiter string is "[stop]".

2b) Split a string delimited by another string and return all elements:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>

2c) Split a string delimited by another string and return all non-empty elements:
The return value contains these 3 elements:
<ONE><TWO><THREE>

2d) Split a string delimited by another string and return 2 elements:
The return value contains these 2 elements:
<><ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]>

2e) Split a string delimited by another string and return 2 non-empty elements:
The return value contains these 2 elements:
<ONE><TWO[stop][stop][stop]THREE[stop][stop]>

*)
    Dim s1 As String = ",ONE,,TWO,,,THREE,,"
    Dim s2 As String = "[stop]" &
                       "ONE[stop][stop]" &
                       "TWO[stop][stop][stop]" &
                       "THREE[stop][stop]"
    Dim charSeparators() As Char = {","c}
    Dim stringSeparators() As String = {"[stop]"}
    Dim result() As String
    ' ------------------------------------------------------------------------------
    ' Split a string delimited by characters.
    ' ------------------------------------------------------------------------------
    Console.WriteLine("1) Split a string delimited by characters:" & vbCrLf)

    ' Display the original string and delimiter characters.
    Console.WriteLine("1a) The original string is ""{0}"".", s1)
    Console.WriteLine("The delimiter character is '{0}'." & vbCrLf, charSeparators(0))

    ' Split a string delimited by characters and return all elements.
    Console.WriteLine("1b) Split a string delimited by characters and " &
                      "return all elements:")
    result = s1.Split(charSeparators, StringSplitOptions.None)
    Show(result)

    ' Split a string delimited by characters and return all non-empty elements.
    Console.WriteLine("1c) Split a string delimited by characters and " &
                      "return all non-empty elements:")
    result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries)
    Show(result)

    ' Split the original string into the string and empty string before the 
    ' delimiter and the remainder of the original string after the delimiter.
    Console.WriteLine("1d) Split a string delimited by characters and " &
                      "return 2 elements:")
    result = s1.Split(charSeparators, 2, StringSplitOptions.None)
    Show(result)

    ' Split the original string into the string after the delimiter and the 
    ' remainder of the original string after the delimiter.
    Console.WriteLine("1e) Split a string delimited by characters and " &
                      "return 2 non-empty elements:")
    result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
    Show(result)

    ' ------------------------------------------------------------------------------
    ' Split a string delimited by another string.
    ' ------------------------------------------------------------------------------
    Console.WriteLine("2) Split a string delimited by another string:" & vbCrLf)

    ' Display the original string and delimiter string.
    Console.WriteLine("2a) The original string is ""{0}"".", s2)
    Console.WriteLine("The delimiter string is ""{0}""." & vbCrLf, stringSeparators(0))

    ' Split a string delimited by another string and return all elements.
    Console.WriteLine("2b) Split a string delimited by another string and " &
                      "return all elements:")
    result = s2.Split(stringSeparators, StringSplitOptions.None)
    Show(result)

    ' Split the original string at the delimiter and return all non-empty elements.
    Console.WriteLine("2c) Split a string delimited by another string and " &
                      "return all non-empty elements:")
    result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)
    Show(result)

    ' Split the original string into the empty string before the 
    ' delimiter and the remainder of the original string after the delimiter.
    Console.WriteLine("2d) Split a string delimited by another string and " &
                      "return 2 elements:")
    result = s2.Split(stringSeparators, 2, StringSplitOptions.None)
    Show(result)

    ' Split the original string into the string after the delimiter and the 
    ' remainder of the original string after the delimiter.
    Console.WriteLine("2e) Split a string delimited by another string and " &
                      "return 2 non-empty elements:")
    result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
    Show(result)

End Sub


' Display the array of separated strings.
Public Shared Sub Show(ByVal entries() As String)
    Console.WriteLine("The return value contains these {0} elements:", entries.Length)
    Dim entry As String
    For Each entry In entries
        Console.Write("<{0}>", entry)
    Next entry
    Console.Write(vbCrLf & vbCrLf)

End Sub

'This example produces the following results:
'
'1) Split a string delimited by characters:
'
'1a) The original string is ",ONE,,TWO,,,THREE,,".
'The delimiter character is ','.
'
'1b) Split a string delimited by characters and return all elements:
'The return value contains these 9 elements:
'<><ONE><><TWO><><><THREE><><>
'
'1c) Split a string delimited by characters and return all non-empty elements:
'The return value contains these 3 elements:
'<ONE><TWO><THREE>
'
'1d) Split a string delimited by characters and return 2 elements:
'The return value contains these 2 elements:
'<><ONE,,TWO,,,THREE,,>
'
'1e) Split a string delimited by characters and return 2 non-empty elements:
'The return value contains these 2 elements:
'<ONE><TWO,,,THREE,,>
'
'2) Split a string delimited by another string:
'
'2a) The original string is "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".
'The delimiter string is "[stop]".
'
'2b) Split a string delimited by another string and return all elements:
'The return value contains these 9 elements:
'<><ONE><><TWO><><><THREE><><>
'
'2c) Split a string delimited by another string and return all non-empty elements:
'The return value contains these 3 elements:
'<ONE><TWO><THREE>
'
'2d) Split a string delimited by another string and return 2 elements:
'The return value contains these 2 elements:
'<><ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]>
'
'2e) Split a string delimited by another string and return 2 non-empty elements:
'The return value contains these 2 elements:
'<ONE><TWO[stop][stop][stop]THREE[stop][stop]>
'

Comentários

Os caracteres delimitadores (os caracteres na separator matriz) não são incluídos nos elementos da matriz retornada. Por exemplo, se a separator matriz incluir o caractere "-" e o valor da instância de cadeia de caracteres atual for "aa-bb-cc", o método retornará uma matriz que contém três elementos: "aa", "bb" e "cc".

Se essa instância não contiver nenhum dos caracteres no separator, a matriz retornada consistirá em um único elemento que contém essa instância.

Se o options parâmetro for RemoveEmptyEntries e o comprimento dessa instância for zero, o método retornará uma matriz vazia.

Cada elemento de separator define um delimitador separado que consiste em um único caractere. Se o options argumento for None, e dois delimitadores forem adjacentes ou um delimitador for encontrado no início ou no final dessa instância, o elemento de matriz correspondente conterá String.Empty. Por exemplo, se separator inclui dois elementos '-' e '_', o valor da instância de cadeia de caracteres é "-_aa-_", e o valor do options argumento é None, o método retorna uma matriz de cadeia de caracteres com os cinco elementos a seguir:

  1. String.Empty, que representa a cadeia de caracteres vazia que precede o caractere "-" no índice 0.

  2. String.Empty, que representa a cadeia de caracteres vazia entre o caractere "-" no índice 0 e o caractere "_" no índice 1.

  3. "aa".

  4. String.Empty, que representa a cadeia de caracteres vazia que segue o caractere "-" no índice 4.

  5. String.Empty, que representa a cadeia de caracteres vazia que segue o caractere "_" no índice 5.

A matriz separadora

Caso o parâmetro separator seja null ou não contenha nenhum caractere, os caracteres de espaço em branco devem ser considerados os delimitadores. Os caracteres de espaço em branco são definidos pelo padrão Unicode e o Char.IsWhiteSpace método retorna true se eles são passados para ele.

Para passar null para o char[] separator parâmetro , você deve indicar o tipo do null para desambiguar a chamada de algumas outras sobrecargas, como Split(String[], StringSplitOptions). O exemplo a seguir mostra várias maneiras para identificar sem ambiguidade essa sobrecarga.

string phrase = "The quick  brown fox";

_ = phrase.Split(default(char[]), StringSplitOptions.RemoveEmptyEntries);

_ = phrase.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries);

_ = phrase.Split(null as char[], StringSplitOptions.RemoveEmptyEntries);
let phrase = "The quick  brown fox"

phrase.Split(Unchecked.defaultof<char[]>, StringSplitOptions.RemoveEmptyEntries) |> ignore

phrase.Split(null :> char[], StringSplitOptions.RemoveEmptyEntries) |> ignore

phrase.Split((null: char[]), StringSplitOptions.RemoveEmptyEntries) |> ignore
Dim phrase As String = "The quick brown fox"
Dim words() As String

words = phrase.Split(TryCast(Nothing, Char()),
                       StringSplitOptions.RemoveEmptyEntries)

words = phrase.Split(New Char() {},
                     StringSplitOptions.RemoveEmptyEntries)

Detalhes da comparação

O Split método extrai as subcadeias de caracteres nessa cadeia de caracteres delimitadas por um ou mais caracteres no separator parâmetro e retorna essas subcadeias de caracteres como elementos de uma matriz.

O Split método procura delimitadores executando comparações usando regras de classificação ordinal que diferenciam maiúsculas de minúsculas. Para obter mais informações sobre as classificações de palavra, cadeia de caracteres e ordinal, consulte a System.Globalization.CompareOptions enumeração .

Considerações sobre o desempenho

Os métodos Split alocam memória para o objeto de matriz retornado e um objeto String para cada elemento da matriz. Caso o aplicativo exija desempenho ideal ou em caso de gerenciamento da alocação da memória ser importante no aplicativo, considere o uso do método IndexOf ou IndexOfAny, e opcionalmente o método de Compare para localizar uma subcadeia de caracteres dentro de uma cadeia de caracteres.

Caso você esteja dividindo uma cadeia de caracteres em um separador de caractere, use o método IndexOf ou IndexOfAny para localizar um caractere separador na cadeia de caracteres. Caso você esteja dividindo uma cadeia de caracteres em uma cadeia de caracteres separadora, use o método IndexOf ou de IndexOfAny para localizar o primeiro caractere da cadeia de caracteres separadora. Em seguida, use o método Compare para determinar se os caracteres depois desse primeiro caractere são iguais aos caracteres restantes da cadeia de caracteres separadora.

Além disso, caso o mesmo conjunto de caracteres seja usado para dividir cadeias de caracteres em várias chamadas de método Split, considere criar uma matriz única e referencie-a em cada chamada de método. Isso reduz significativamente a sobrecarga adicional de cada chamada de método.

Notas aos Chamadores

No .NET Framework 3.5 e versões anteriores, se o Split(Char[]) método for passado um separator que seja null ou não contenha caracteres, o método usará um conjunto ligeiramente diferente de caracteres de espaço em branco para dividir a cadeia de caracteres do que o Trim(Char[]) método faz para cortar a cadeia de caracteres. Começando com .NET Framework 4, ambos os métodos usam um conjunto idêntico de caracteres de espaço em branco Unicode.

Aplica-se a

Split(String, StringSplitOptions)

Divide uma cadeia de caracteres em substrings com base no separador de cadeias de caracteres fornecido.

public string[] Split (string? separator, StringSplitOptions options = System.StringSplitOptions.None);
public string[] Split (string separator, StringSplitOptions options = System.StringSplitOptions.None);
member this.Split : string * StringSplitOptions -> string[]
Public Function Split (separator As String, Optional options As StringSplitOptions = System.StringSplitOptions.None) As String()

Parâmetros

separator
String

Uma cadeia de caracteres que delimita as substrings nesta cadeia de caracteres.

options
StringSplitOptions

Uma combinação bit a bit dos valores de enumeração que especifica se substrings devem ser cortadas e se substrings vazias devem ser incluídas.

Retornos

String[]

Uma matriz cujos elementos contêm as subcadeias de caracteres desta instância que são delimitadas por separator.

Aplica-se a

Split(String[], StringSplitOptions)

Divide uma cadeia de caracteres em substrings baseadas em uma cadeia de caracteres delimitadora especificada e, opcionalmente, em opções.

public:
 cli::array <System::String ^> ^ Split(cli::array <System::String ^> ^ separator, StringSplitOptions options);
public string[] Split (string[] separator, StringSplitOptions options);
public string[] Split (string[]? separator, StringSplitOptions options);
[System.Runtime.InteropServices.ComVisible(false)]
public string[] Split (string[] separator, StringSplitOptions options);
member this.Split : string[] * StringSplitOptions -> string[]
[<System.Runtime.InteropServices.ComVisible(false)>]
member this.Split : string[] * StringSplitOptions -> string[]
Public Function Split (separator As String(), options As StringSplitOptions) As String()

Parâmetros

separator
String[]

Uma matriz de cadeias de caracteres que delimitam as substrings nesta cadeia de caracteres, uma matriz vazia que não contém delimitadores ou null.

options
StringSplitOptions

Uma combinação bit a bit dos valores de enumeração que especifica se substrings devem ser cortadas e se substrings vazias devem ser incluídas.

Retornos

String[]

Uma matriz cujos elementos contêm as subcadeias de caracteres desta cadeia de caracteres que são delimitadas por uma ou mais cadeias de caracteres em separator. Para obter mais informações, consulte a seção Comentários.

Atributos

Exceções

options não é um dos valores StringSplitOptions.

Exemplos

O exemplo a seguir ilustra a diferença nas matrizes retornadas chamando o método de uma cadeia de String.Split(String[], StringSplitOptions) caracteres com seu options parâmetro igual a StringSplitOptions.None e StringSplitOptions.RemoveEmptyEntries.

string source = "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]";
string[] stringSeparators = new string[] { "[stop]" };
string[] result;

// Display the original string and delimiter string.
Console.WriteLine($"Splitting the string:\n   \"{source}\".");
Console.WriteLine();
Console.WriteLine($"Using the delimiter string:\n   \"{stringSeparators[0]}\"");
Console.WriteLine();

// Split a string delimited by another string and return all elements.
result = source.Split(stringSeparators, StringSplitOptions.None);
Console.WriteLine($"Result including all elements ({result.Length} elements):");
Console.Write("   ");
foreach (string s in result)
{
    Console.Write("'{0}' ", String.IsNullOrEmpty(s) ? "<>" : s);
}
Console.WriteLine();
Console.WriteLine();

// Split delimited by another string and return all non-empty elements.
result = source.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);
Console.WriteLine($"Result including non-empty elements ({result.Length} elements):");
Console.Write("   ");
foreach (string s in result)
{
    Console.Write("'{0}' ", String.IsNullOrEmpty(s) ? "<>" : s);
}
Console.WriteLine();

// The example displays the following output:
//    Splitting the string:
//       "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".
//    
//    Using the delimiter string:
//       "[stop]"
//    
//    Result including all elements (9 elements):
//       '<>' 'ONE' '<>' 'TWO' '<>' '<>' 'THREE' '<>' '<>'
//    
//    Result including non-empty elements (3 elements):
//       'ONE' 'TWO' 'THREE'
let source = "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]"
let stringSeparators = [| "[stop]" |]

// Display the original string and delimiter string.
printfn $"Splitting the string:\n   \"{source}\".\n"
printfn $"Using the delimiter string:\n   \"{stringSeparators[0]}\"\n"

// Split a string delimited by another string and return all elements.
let result = source.Split(stringSeparators, StringSplitOptions.None)
printfn $"Result including all elements ({result.Length} elements):"
printf "   "
for s in result do
    printf $"""'{if String.IsNullOrEmpty s then "<>" else s}' """
printfn "\n"

// Split delimited by another string and return all non-empty elements.
let result = source.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)
Console.WriteLine($"Result including non-empty elements ({result.Length} elements):")
printf "   "
for s in result do
    printf $"""'{if String.IsNullOrEmpty s then "<>" else s}' """
printfn ""

// The example displays the following output:
//    Splitting the string:
//       "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".
//    
//    Using the delimiter string:
//       "[stop]"
//    
//    let result including all elements (9 elements):
//       '<>' 'ONE' '<>' 'TWO' '<>' '<>' 'THREE' '<>' '<>'
//    
//    let result including non-empty elements (3 elements):
//       'ONE' 'TWO' 'THREE'
Dim source As String = "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]"
Dim stringSeparators() As String = {"[stop]"}
Dim result() As String

' Display the original string and delimiter string.
Console.WriteLine("Splitting the string:{0}   '{1}'.", vbCrLf, source)
Console.WriteLine()
Console.WriteLine("Using the delimiter string:{0}   '{1}'.",
                vbCrLf, stringSeparators(0))
Console.WriteLine()

' Split a string delimited by another string and return all elements.
result = source.Split(stringSeparators, StringSplitOptions.None)
Console.WriteLine("Result including all elements ({0} elements):",
                result.Length)
Console.Write("   ")
For Each s As String In result
    Console.Write("'{0}' ", IIf(String.IsNullOrEmpty(s), "<>", s))
Next
Console.WriteLine()
Console.WriteLine()

' Split delimited by another string and return all non-empty elements.
result = source.Split(stringSeparators,
                    StringSplitOptions.RemoveEmptyEntries)
Console.WriteLine("Result including non-empty elements ({0} elements):",
                result.Length)
Console.Write("   ")
For Each s As String In result
    Console.Write("'{0}' ", IIf(String.IsNullOrEmpty(s), "<>", s))
Next
Console.WriteLine()

' The example displays the following output:
'    Splitting the string:
'       "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".
'    
'    Using the delimiter string:
'       "[stop]"
'    
'    Result including all elements (9 elements):
'       '<>' 'ONE' '<>' 'TWO' '<>' '<>' 'THREE' '<>' '<>'
'    
'    Result including non-empty elements (3 elements):
'       'ONE' 'TWO' 'THREE'

O exemplo a seguir define uma matriz de separadores que incluem caracteres de pontuação e espaço em branco. Passar essa matriz junto com um valor de StringSplitOptions.RemoveEmptyEntries para o Split(String[], StringSplitOptions) método retorna uma matriz que consiste nas palavras individuais da cadeia de caracteres.

string[] separators = { ",", ".", "!", "?", ";", ":", " " };
string value = "The handsome, energetic, young dog was playing with his smaller, more lethargic litter mate.";
string[] words = value.Split(separators, StringSplitOptions.RemoveEmptyEntries);
foreach (var word in words)
    Console.WriteLine(word);

// The example displays the following output:
//       The
//       handsome
//       energetic
//       young
//       dog
//       was
//       playing
//       with
//       his
//       smaller
//       more
//       lethargic
//       litter
//       mate
let separators = [| ","; "."; "!"; "?"; ""; ":"; " " |]
let value = "The handsome, energetic, young dog was playing with his smaller, more lethargic litter mate."
let words = value.Split(separators, StringSplitOptions.RemoveEmptyEntries)
for word in words do
    printfn $"${word}"

// The example displays the following output:
//       The
//       handsome
//       energetic
//       young
//       dog
//       was
//       playing
//       with
//       his
//       smaller
//       more
//       lethargic
//       litter
//       mate
    Dim separators() As String = {",", ".", "!", "?", ";", ":", " "}
    Dim value As String = "The handsome, energetic, young dog was playing with his smaller, more lethargic litter mate."
    Dim words() As String = value.Split(separators, StringSplitOptions.RemoveEmptyEntries)
    For Each word In words
        Console.WriteLine(word)
    Next
End Sub

' The example displays the following output:
'
'       The
'       handsome
'       energetic
'       young
'       dog
'       was
'       playing
'       with
'       his
'       smaller
'       more
'       lethargic
'       litter
'       mate

Observe que o método é chamado com o options argumento definido como StringSplitOptions.RemoveEmptyEntries. Isso impede que a matriz retornada inclua String.Empty valores que representam correspondências de subcadeia de caracteres vazias entre marcas de pontuação e caracteres de espaço em branco.

Comentários

Quando uma cadeia de caracteres é delimitada por um conjunto conhecido de cadeias de caracteres, você pode usar o Split método para separá-la em subcadeias de caracteres.

As cadeias de caracteres delimitador não são incluídas nos elementos da matriz retornada. Por exemplo, se a separator matriz incluir a cadeia de caracteres "--" e o valor da instância de cadeia de caracteres atual for "aa--bb--cc", o método retornará uma matriz que contém três elementos: "aa", "bb" e "cc".

Se essa instância não contiver nenhuma das cadeias de caracteres no separator, a matriz retornada consistirá em um único elemento que contém essa instância.

Se o options parâmetro for RemoveEmptyEntries e o comprimento dessa instância for zero, o método retornará uma matriz vazia.

Cada elemento de separator define um delimitador separado que consiste em um ou mais caracteres. Se o options argumento for None, e dois delimitadores forem adjacentes ou um delimitador for encontrado no início ou no final dessa instância, o elemento de matriz correspondente conterá String.Empty. Por exemplo, se separator incluir dois elementos, "-" e "_", o valor da instância de cadeia de caracteres será "-_aa-_", e o valor do options argumento for None, o método retornará uma matriz de cadeia de caracteres com os cinco elementos a seguir:

  1. String.Empty, que representa a cadeia de caracteres vazia que precede a subcadeia de caracteres "-" no índice 0.

  2. String.Empty, que representa a cadeia de caracteres vazia entre a subcadeia de caracteres "-" no índice 0 e a subcadeia de caracteres "_" no índice 1.

  3. "aa".

  4. String.Empty, que representa a cadeia de caracteres vazia que segue a subcadeia de caracteres "-" no índice 4.

  5. String.Empty, que representa a cadeia de caracteres vazia que segue a subcadeia de caracteres "_" no índice 5.

A matriz separadora

Se qualquer um dos elementos em consistir em separator vários caracteres, toda a subcadeia de caracteres será considerada um delimitador. Por exemplo, se um dos elementos em separator for "10", tentar dividir a cadeia de caracteres "This10is10a10string" retornará a seguinte matriz de quatro elementos: { "This", "is", "a", "string". }.

Se o separator parâmetro for null ou não contiver cadeias de caracteres não vazias, os caracteres de espaço em branco serão considerados delimitadores. Os caracteres de espaço em branco são definidos pelo padrão Unicode e o Char.IsWhiteSpace método retorna true se eles são passados para ele.

Para passar null para o string[] separator parâmetro , você deve indicar o tipo do null para desambiguar a chamada de algumas outras sobrecargas, como Split(Char[], StringSplitOptions). O exemplo a seguir mostra várias maneiras para identificar sem ambiguidade essa sobrecarga.

string phrase = "The quick  brown fox";

_ = phrase.Split(default(string[]), StringSplitOptions.RemoveEmptyEntries);

_ = phrase.Split((string[]?)null, StringSplitOptions.RemoveEmptyEntries);

_ = phrase.Split(null as string[], StringSplitOptions.RemoveEmptyEntries);
let phrase = "The quick  brown fox"

phrase.Split(Unchecked.defaultof<string[]>, StringSplitOptions.RemoveEmptyEntries) |> ignore

phrase.Split(null :> string[], StringSplitOptions.RemoveEmptyEntries) |> ignore

phrase.Split((null: string[]), StringSplitOptions.RemoveEmptyEntries) |> ignore
Dim phrase As String = "The quick brown fox"
Dim words() As String

words = phrase.Split(TryCast(Nothing, String()),
                       StringSplitOptions.RemoveEmptyEntries)

words = phrase.Split(New String() {},
                     StringSplitOptions.RemoveEmptyEntries)

Detalhes da comparação

O Split método extrai as subcadeias de caracteres nessa cadeia de caracteres delimitadas por uma ou mais das cadeias de caracteres no separator parâmetro e retorna essas subcadeias de caracteres como elementos de uma matriz.

O Split método procura delimitadores executando comparações usando regras de classificação ordinal que diferenciam maiúsculas de minúsculas. Para obter mais informações sobre as classificações de palavra, cadeia de caracteres e ordinal, consulte a System.Globalization.CompareOptions enumeração .

O Split método ignora qualquer elemento de separator cujo valor é null ou a cadeia de caracteres vazia ("").

Para evitar resultados ambíguos quando cadeias de caracteres em separator têm caracteres em comum, a Split operação prossegue do início ao fim do valor da instância e corresponde ao primeiro elemento em separator que é igual a um delimitador na instância. A ordem na qual as subcadeias de caracteres são encontradas na instância tem precedência sobre a ordem dos elementos em separator.

Por exemplo, considere uma instância cujo valor é "abcdef". Se o primeiro elemento em separator fosse "ef" e o segundo elemento fosse "bcde", o resultado da operação de divisão seria uma matriz de cadeia de caracteres que contém dois elementos, "a" e "f". Isso ocorre porque a subcadeia de caracteres na instância , "bcde", é encontrada e corresponde a um elemento em separator antes da subcadeia de caracteres "f" ser encontrada.

No entanto, se o primeiro elemento de separator fosse "bcd" e o segundo elemento fosse "bc", o resultado da operação de divisão seria uma matriz de cadeia de caracteres que contém dois elementos, "a" e "ef". Isso ocorre porque "bcd" é o primeiro delimitador em separator que corresponde a um delimitador na instância. Se a ordem dos separadores foi invertida para que o primeiro elemento fosse "bc" e o segundo elemento fosse "bcd", o resultado seria uma matriz de cadeia de caracteres que contém dois elementos, "a" e "def".

Considerações sobre o desempenho

Os métodos Split alocam memória para o objeto de matriz retornado e um objeto String para cada elemento da matriz. Caso o aplicativo exija desempenho ideal ou em caso de gerenciamento da alocação da memória ser importante no aplicativo, considere o uso do método IndexOf ou IndexOfAny, e opcionalmente o método de Compare para localizar uma subcadeia de caracteres dentro de uma cadeia de caracteres.

Caso você esteja dividindo uma cadeia de caracteres em um separador de caractere, use o método IndexOf ou IndexOfAny para localizar um caractere separador na cadeia de caracteres. Caso você esteja dividindo uma cadeia de caracteres em uma cadeia de caracteres separadora, use o método IndexOf ou de IndexOfAny para localizar o primeiro caractere da cadeia de caracteres separadora. Em seguida, use o método Compare para determinar se os caracteres depois desse primeiro caractere são iguais aos caracteres restantes da cadeia de caracteres separadora.

Além disso, caso o mesmo conjunto de caracteres seja usado para dividir cadeias de caracteres em várias chamadas de método Split, considere criar uma matriz única e referencie-a em cada chamada de método. Isso reduz significativamente a sobrecarga adicional de cada chamada de método.

Notas aos Chamadores

No .NET Framework 3.5 e versões anteriores, se o Split(Char[]) método for passado um separator que seja null ou não contenha caracteres, o método usará um conjunto ligeiramente diferente de caracteres de espaço em branco para dividir a cadeia de caracteres do que o Trim(Char[]) método faz para cortar a cadeia de caracteres. Começando com .NET Framework 4, ambos os métodos usam um conjunto idêntico de caracteres de espaço em branco Unicode.

Aplica-se a

Split(Char, Int32, StringSplitOptions)

Divide uma cadeia de caracteres em um número máximo de substrings baseadas em um caractere delimitador especificado e, opcionalmente, em opções. Divide uma cadeia de caracteres em um número máximo de substrings baseadas no separador de caracteres fornecido, omitindo opcionalmente substrings vazias do resultado.

public string[] Split (char separator, int count, StringSplitOptions options = System.StringSplitOptions.None);
member this.Split : char * int * StringSplitOptions -> string[]
Public Function Split (separator As Char, count As Integer, Optional options As StringSplitOptions = System.StringSplitOptions.None) As String()

Parâmetros

separator
Char

Um caractere que delimita as substrings nesta instância.

count
Int32

O número máximo de elementos esperados na matriz.

options
StringSplitOptions

Uma combinação bit a bit dos valores de enumeração que especifica se substrings devem ser cortadas e se substrings vazias devem ser incluídas.

Retornos

String[]

Uma matriz que contém no máximo count substrings desta instância que são delimitadas por separator.

Comentários

Se a cadeia de caracteres já tiver sido dividida count - 1 vezes, mas o final da cadeia de caracteres não tiver sido atingido, a última cadeia de caracteres na matriz retornada conterá a subcadeia de caracteres restante dessa instância, intocada.

Aplica-se a

Split(Char[], Int32, StringSplitOptions)

Divide uma cadeia de caracteres em um número máximo de substrings baseadas em caracteres delimitadores especificados e, opcionalmente, em opções.

public:
 cli::array <System::String ^> ^ Split(cli::array <char> ^ separator, int count, StringSplitOptions options);
public string[] Split (char[] separator, int count, StringSplitOptions options);
public string[] Split (char[]? separator, int count, StringSplitOptions options);
[System.Runtime.InteropServices.ComVisible(false)]
public string[] Split (char[] separator, int count, StringSplitOptions options);
member this.Split : char[] * int * StringSplitOptions -> string[]
[<System.Runtime.InteropServices.ComVisible(false)>]
member this.Split : char[] * int * StringSplitOptions -> string[]
Public Function Split (separator As Char(), count As Integer, options As StringSplitOptions) As String()

Parâmetros

separator
Char[]

Uma matriz de caracteres que delimitam as substrings nesta cadeia de caracteres, uma matriz vazia que não contém delimitadores ou null.

count
Int32

O número máximo de subcadeias de caracteres a serem retornadas.

options
StringSplitOptions

Uma combinação bit a bit dos valores de enumeração que especifica se substrings devem ser cortadas e se substrings vazias devem ser incluídas.

Retornos

String[]

Uma matriz que contém as substrings dessa cadeia de caracteres que são delimitadas por um ou mais caracteres em separator. Para obter mais informações, consulte a seção Comentários.

Atributos

Exceções

count é negativo.

options não é um dos valores StringSplitOptions.

Exemplos

O exemplo a seguir usa a StringSplitOptions enumeração para incluir ou excluir subcadeias de caracteres geradas pelo Split método .

// This example demonstrates the String.Split(Char[], Boolean) and 
//                               String.Split(Char[], Int32, Boolean) methods
using namespace System;
void Show( array<String^>^entries )
{
   Console::WriteLine( "The return value contains these {0} elements:", entries->Length );
   System::Collections::IEnumerator^ myEnum = entries->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      String^ entry = safe_cast<String^>(myEnum->Current);
      Console::Write( "<{0}>", entry );
   }

   Console::Write( "{0}{0}", Environment::NewLine );
}

int main()
{
   String^ s = ",one,,,two,,,,,three,,";
   array<Char>^sep = gcnew array<Char>{
      ','
   };
   array<String^>^result;
   
   //
   Console::WriteLine( "The original string is \"{0}\".", s );
   Console::WriteLine( "The separation character is '{0}'.", sep[ 0 ] );
   Console::WriteLine();
   
   //
   Console::WriteLine( "Split the string and return all elements:" );
   result = s->Split( sep, StringSplitOptions::None );
   Show( result );
   
   //
   Console::WriteLine( "Split the string and return all non-empty elements:" );
   result = s->Split( sep, StringSplitOptions::RemoveEmptyEntries );
   Show( result );
   
   //
   Console::WriteLine( "Split the string and return 2 elements:" );
   result = s->Split( sep, 2, StringSplitOptions::None );
   Show( result );
   
   //
   Console::WriteLine( "Split the string and return 2 non-empty elements:" );
   result = s->Split( sep, 2, StringSplitOptions::RemoveEmptyEntries );
   Show( result );
}

/*
This example produces the following results:

The original string is ",one,,,two,,,,,three,,".
The separation character is ','.

Split the string and return all elements:
The return value contains these 12 elements:
<><one><><><two><><><><><three><><>

Split the string and return all non-empty elements:
The return value contains these 3 elements:
<one><two><three>

Split the string and return 2 elements:
The return value contains these 2 elements:
<><one,,,two,,,,,three,,>

Split the string and return 2 non-empty elements:
The return value contains these 2 elements:
<one><,,two,,,,,three,,>

*/
// This example demonstrates the String.Split() methods that use
// the StringSplitOptions enumeration.
string s1 = ",ONE,,TWO,,,THREE,,";
string s2 = "[stop]" +
            "ONE[stop][stop]" +
            "TWO[stop][stop][stop]" +
            "THREE[stop][stop]";
char[] charSeparators = new char[] { ',' };
string[] stringSeparators = new string[] { "[stop]" };
string[] result;
// ------------------------------------------------------------------------------
// Split a string delimited by characters.
// ------------------------------------------------------------------------------
Console.WriteLine("1) Split a string delimited by characters:\n");

// Display the original string and delimiter characters.
Console.WriteLine($"1a) The original string is \"{s1}\".");
Console.WriteLine($"The delimiter character is '{charSeparators[0]}'.\n");

// Split a string delimited by characters and return all elements.
Console.WriteLine("1b) Split a string delimited by characters and " +
                  "return all elements:");
result = s1.Split(charSeparators, StringSplitOptions.None);
Show(result);

// Split a string delimited by characters and return all non-empty elements.
Console.WriteLine("1c) Split a string delimited by characters and " +
                  "return all non-empty elements:");
result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);
Show(result);

// Split the original string into the string and empty string before the
// delimiter and the remainder of the original string after the delimiter.
Console.WriteLine("1d) Split a string delimited by characters and " +
                  "return 2 elements:");
result = s1.Split(charSeparators, 2, StringSplitOptions.None);
Show(result);

// Split the original string into the string after the delimiter and the
// remainder of the original string after the delimiter.
Console.WriteLine("1e) Split a string delimited by characters and " +
                  "return 2 non-empty elements:");
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries);
Show(result);

// ------------------------------------------------------------------------------
// Split a string delimited by another string.
// ------------------------------------------------------------------------------
Console.WriteLine("2) Split a string delimited by another string:\n");

// Display the original string and delimiter string.
Console.WriteLine($"2a) The original string is \"{s2}\".");
Console.WriteLine($"The delimiter string is \"{stringSeparators[0]}\".\n");

// Split a string delimited by another string and return all elements.
Console.WriteLine("2b) Split a string delimited by another string and " +
                  "return all elements:");
result = s2.Split(stringSeparators, StringSplitOptions.None);
Show(result);

// Split the original string at the delimiter and return all non-empty elements.
Console.WriteLine("2c) Split a string delimited by another string and " +
                  "return all non-empty elements:");
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);
Show(result);

// Split the original string into the empty string before the
// delimiter and the remainder of the original string after the delimiter.
Console.WriteLine("2d) Split a string delimited by another string and " +
                  "return 2 elements:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.None);
Show(result);

// Split the original string into the string after the delimiter and the
// remainder of the original string after the delimiter.
Console.WriteLine("2e) Split a string delimited by another string and " +
                  "return 2 non-empty elements:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries);
Show(result);

// Display the array of separated strings using a local function
void Show(string[] entries)
{
    Console.WriteLine($"The return value contains these {entries.Length} elements:");
    foreach (string entry in entries)
    {
        Console.Write($"<{entry}>");
    }
    Console.Write("\n\n");
}

/*
This example produces the following results:

1) Split a string delimited by characters:

1a) The original string is ",ONE,,TWO,,,THREE,,".
The delimiter character is ','.

1b) Split a string delimited by characters and return all elements:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>

1c) Split a string delimited by characters and return all non-empty elements:
The return value contains these 3 elements:
<ONE><TWO><THREE>

1d) Split a string delimited by characters and return 2 elements:
The return value contains these 2 elements:
<><ONE,,TWO,,,THREE,,>

1e) Split a string delimited by characters and return 2 non-empty elements:
The return value contains these 2 elements:
<ONE><TWO,,,THREE,,>

2) Split a string delimited by another string:

2a) The original string is "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".
The delimiter string is "[stop]".

2b) Split a string delimited by another string and return all elements:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>

2c) Split a string delimited by another string and return all non-empty elements:
The return value contains these 3 elements:
<ONE><TWO><THREE>

2d) Split a string delimited by another string and return 2 elements:
The return value contains these 2 elements:
<><ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]>

2e) Split a string delimited by another string and return 2 non-empty elements:
The return value contains these 2 elements:
<ONE><TWO[stop][stop][stop]THREE[stop][stop]>

*/
// This example demonstrates the String.Split() methods that use
// the StringSplitOptions enumeration.
 
// Display the array of separated strings using a local function
let show  (entries: string[]) =
    printfn $"The return value contains these {entries.Length} elements:"
    for entry in entries do
        printf $"<{entry}>"
    printf "\n\n"

let s1 = ",ONE,,TWO,,,THREE,,"
let s2 = "[stop]" +
         "ONE[stop][stop]" +
         "TWO[stop][stop][stop]" +
         "THREE[stop][stop]"
let charSeparators = [| ',' |]
let stringSeparators = [| "[stop]" |]
// ------------------------------------------------------------------------------
// Split a string delimited by characters.
// ------------------------------------------------------------------------------
printfn "1) Split a string delimited by characters:\n"

// Display the original string and delimiter characters.
printfn $"1a) The original string is \"{s1}\"."
printfn $"The delimiter character is '{charSeparators[0]}'.\n"

// Split a string delimited by characters and return all elements.
printfn "1b) Split a string delimited by characters and return all elements:"
let result = s1.Split(charSeparators, StringSplitOptions.None)
show result

// Split a string delimited by characters and return all non-empty elements.
printfn "1c) Split a string delimited by characters and return all non-empty elements:"
let result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries)
show result

// Split the original string into the string and empty string before the
// delimiter and the remainder of the original string after the delimiter.
printfn "1d) Split a string delimited by characters and return 2 elements:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.None)
show result

// Split the original string into the string after the delimiter and the
// remainder of the original string after the delimiter.
printfn "1e) Split a string delimited by characters and return 2 non-empty elements:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
show result

// ------------------------------------------------------------------------------
// Split a string delimited by another string.
// ------------------------------------------------------------------------------
printfn "2) Split a string delimited by another string:\n"

// Display the original string and delimiter string.
printfn $"2a) The original string is \"{s2}\"."
printfn $"The delimiter string is \"{stringSeparators[0]}\".\n"

// Split a string delimited by another string and return all elements.
printfn "2b) Split a string delimited by another string and return all elements:"
let result = s2.Split(stringSeparators, StringSplitOptions.None)
show result

// Split the original string at the delimiter and return all non-empty elements.
printfn "2c) Split a string delimited by another string and return all non-empty elements:"
let result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)
show result

// Split the original string into the empty string before the
// delimiter and the remainder of the original string after the delimiter.
printfn "2d) Split a string delimited by another string and return 2 elements:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.None)
show result

// Split the original string into the string after the delimiter and the
// remainder of the original string after the delimiter.
printfn "2e) Split a string delimited by another string and return 2 non-empty elements:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
show result

(*
This example produces the following results:

1) Split a string delimited by characters:

1a) The original string is ",ONE,,TWO,,,THREE,,".
The delimiter character is ','.

1b) Split a string delimited by characters and return all elements:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>

1c) Split a string delimited by characters and return all non-empty elements:
The return value contains these 3 elements:
<ONE><TWO><THREE>

1d) Split a string delimited by characters and return 2 elements:
The return value contains these 2 elements:
<><ONE,,TWO,,,THREE,,>

1e) Split a string delimited by characters and return 2 non-empty elements:
The return value contains these 2 elements:
<ONE><TWO,,,THREE,,>

2) Split a string delimited by another string:

2a) The original string is "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".
The delimiter string is "[stop]".

2b) Split a string delimited by another string and return all elements:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>

2c) Split a string delimited by another string and return all non-empty elements:
The return value contains these 3 elements:
<ONE><TWO><THREE>

2d) Split a string delimited by another string and return 2 elements:
The return value contains these 2 elements:
<><ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]>

2e) Split a string delimited by another string and return 2 non-empty elements:
The return value contains these 2 elements:
<ONE><TWO[stop][stop][stop]THREE[stop][stop]>

*)
    Dim s1 As String = ",ONE,,TWO,,,THREE,,"
    Dim s2 As String = "[stop]" &
                       "ONE[stop][stop]" &
                       "TWO[stop][stop][stop]" &
                       "THREE[stop][stop]"
    Dim charSeparators() As Char = {","c}
    Dim stringSeparators() As String = {"[stop]"}
    Dim result() As String
    ' ------------------------------------------------------------------------------
    ' Split a string delimited by characters.
    ' ------------------------------------------------------------------------------
    Console.WriteLine("1) Split a string delimited by characters:" & vbCrLf)

    ' Display the original string and delimiter characters.
    Console.WriteLine("1a) The original string is ""{0}"".", s1)
    Console.WriteLine("The delimiter character is '{0}'." & vbCrLf, charSeparators(0))

    ' Split a string delimited by characters and return all elements.
    Console.WriteLine("1b) Split a string delimited by characters and " &
                      "return all elements:")
    result = s1.Split(charSeparators, StringSplitOptions.None)
    Show(result)

    ' Split a string delimited by characters and return all non-empty elements.
    Console.WriteLine("1c) Split a string delimited by characters and " &
                      "return all non-empty elements:")
    result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries)
    Show(result)

    ' Split the original string into the string and empty string before the 
    ' delimiter and the remainder of the original string after the delimiter.
    Console.WriteLine("1d) Split a string delimited by characters and " &
                      "return 2 elements:")
    result = s1.Split(charSeparators, 2, StringSplitOptions.None)
    Show(result)

    ' Split the original string into the string after the delimiter and the 
    ' remainder of the original string after the delimiter.
    Console.WriteLine("1e) Split a string delimited by characters and " &
                      "return 2 non-empty elements:")
    result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
    Show(result)

    ' ------------------------------------------------------------------------------
    ' Split a string delimited by another string.
    ' ------------------------------------------------------------------------------
    Console.WriteLine("2) Split a string delimited by another string:" & vbCrLf)

    ' Display the original string and delimiter string.
    Console.WriteLine("2a) The original string is ""{0}"".", s2)
    Console.WriteLine("The delimiter string is ""{0}""." & vbCrLf, stringSeparators(0))

    ' Split a string delimited by another string and return all elements.
    Console.WriteLine("2b) Split a string delimited by another string and " &
                      "return all elements:")
    result = s2.Split(stringSeparators, StringSplitOptions.None)
    Show(result)

    ' Split the original string at the delimiter and return all non-empty elements.
    Console.WriteLine("2c) Split a string delimited by another string and " &
                      "return all non-empty elements:")
    result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)
    Show(result)

    ' Split the original string into the empty string before the 
    ' delimiter and the remainder of the original string after the delimiter.
    Console.WriteLine("2d) Split a string delimited by another string and " &
                      "return 2 elements:")
    result = s2.Split(stringSeparators, 2, StringSplitOptions.None)
    Show(result)

    ' Split the original string into the string after the delimiter and the 
    ' remainder of the original string after the delimiter.
    Console.WriteLine("2e) Split a string delimited by another string and " &
                      "return 2 non-empty elements:")
    result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
    Show(result)

End Sub


' Display the array of separated strings.
Public Shared Sub Show(ByVal entries() As String)
    Console.WriteLine("The return value contains these {0} elements:", entries.Length)
    Dim entry As String
    For Each entry In entries
        Console.Write("<{0}>", entry)
    Next entry
    Console.Write(vbCrLf & vbCrLf)

End Sub

'This example produces the following results:
'
'1) Split a string delimited by characters:
'
'1a) The original string is ",ONE,,TWO,,,THREE,,".
'The delimiter character is ','.
'
'1b) Split a string delimited by characters and return all elements:
'The return value contains these 9 elements:
'<><ONE><><TWO><><><THREE><><>
'
'1c) Split a string delimited by characters and return all non-empty elements:
'The return value contains these 3 elements:
'<ONE><TWO><THREE>
'
'1d) Split a string delimited by characters and return 2 elements:
'The return value contains these 2 elements:
'<><ONE,,TWO,,,THREE,,>
'
'1e) Split a string delimited by characters and return 2 non-empty elements:
'The return value contains these 2 elements:
'<ONE><TWO,,,THREE,,>
'
'2) Split a string delimited by another string:
'
'2a) The original string is "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".
'The delimiter string is "[stop]".
'
'2b) Split a string delimited by another string and return all elements:
'The return value contains these 9 elements:
'<><ONE><><TWO><><><THREE><><>
'
'2c) Split a string delimited by another string and return all non-empty elements:
'The return value contains these 3 elements:
'<ONE><TWO><THREE>
'
'2d) Split a string delimited by another string and return 2 elements:
'The return value contains these 2 elements:
'<><ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]>
'
'2e) Split a string delimited by another string and return 2 non-empty elements:
'The return value contains these 2 elements:
'<ONE><TWO[stop][stop][stop]THREE[stop][stop]>
'

Comentários

Os caracteres delimitadores não estão incluídos nos elementos da matriz retornada.

Se essa instância não contiver nenhum dos caracteres em separatorou o count parâmetro for 1, a matriz retornada consistirá em um único elemento que contém essa instância.

Caso o parâmetro separator seja null ou não contenha nenhum caractere, os caracteres de espaço em branco devem ser considerados os delimitadores. Os caracteres de espaço em branco são definidos pelo padrão Unicode e o Char.IsWhiteSpace método retorna true se eles são passados para ele.

Para passar null para o char[] separator parâmetro , você deve indicar o tipo do null para desambiguar a chamada de algumas outras sobrecargas, como Split(String[], Int32, StringSplitOptions). O exemplo a seguir mostra várias maneiras para identificar sem ambiguidade essa sobrecarga.

string phrase = "The quick  brown fox";

_ = phrase.Split(default(char[]), 3, StringSplitOptions.RemoveEmptyEntries);

_ = phrase.Split((char[]?)null, 3, StringSplitOptions.RemoveEmptyEntries);

_ = phrase.Split(null as char[], 3, StringSplitOptions.RemoveEmptyEntries);
let phrase = "The quick  brown fox"

phrase.Split(Unchecked.defaultof<char[]>, 3, StringSplitOptions.RemoveEmptyEntries) |> ignore

phrase.Split(null :> char[], 3, StringSplitOptions.RemoveEmptyEntries) |> ignore

phrase.Split((null: char[]), 3, StringSplitOptions.RemoveEmptyEntries) |> ignore
Dim phrase As String = "The quick brown fox"
Dim words() As String

words = phrase.Split(TryCast(Nothing, Char()), 3,
                       StringSplitOptions.RemoveEmptyEntries)

words = phrase.Split(New Char() {}, 3,
                     StringSplitOptions.RemoveEmptyEntries)

Se o count parâmetro for zero ou o options parâmetro for RemoveEmptyEntries e o comprimento dessa instância for zero, uma matriz vazia será retornada.

Cada elemento de separator define um caractere delimitador à parte. Caso o parâmetro options seja None e dois delimitadores sejam adjacentes ou um delimitador esteja no início ou no fim dessa instância, o elemento da matriz correspondente contém Empty.

Se houver mais de count subcadeias de caracteres nessa instância, as primeiras count subcadeias de caracteres menos 1 serão retornadas nos primeiros count elementos menos 1 do valor retornado e os caracteres restantes nessa instância serão retornados no último elemento do valor retornado.

Se count for maior que o número de subcadeias de caracteres, as subcadeias de caracteres disponíveis serão retornadas e nenhuma exceção será gerada.

Considerações sobre o desempenho

Os métodos Split alocam memória para o objeto de matriz retornado e um objeto String para cada elemento da matriz. Caso o aplicativo exija desempenho ideal ou em caso de gerenciamento da alocação da memória ser importante no aplicativo, considere o uso do método IndexOf ou IndexOfAny, e opcionalmente o método de Compare para localizar uma subcadeia de caracteres dentro de uma cadeia de caracteres.

Caso você esteja dividindo uma cadeia de caracteres em um separador de caractere, use o método IndexOf ou IndexOfAny para localizar um caractere separador na cadeia de caracteres. Caso você esteja dividindo uma cadeia de caracteres em uma cadeia de caracteres separadora, use o método IndexOf ou de IndexOfAny para localizar o primeiro caractere da cadeia de caracteres separadora. Em seguida, use o método Compare para determinar se os caracteres depois desse primeiro caractere são iguais aos caracteres restantes da cadeia de caracteres separadora.

Além disso, caso o mesmo conjunto de caracteres seja usado para dividir cadeias de caracteres em várias chamadas de método Split, considere criar uma matriz única e referencie-a em cada chamada de método. Isso reduz significativamente a sobrecarga adicional de cada chamada de método.

Notas aos Chamadores

No .NET Framework 3.5 e versões anteriores, se o Split(Char[]) método for passado um separator que seja null ou não contenha caracteres, o método usará um conjunto ligeiramente diferente de caracteres de espaço em branco para dividir a cadeia de caracteres do que o Trim(Char[]) método faz para cortar a cadeia de caracteres. Começando com .NET Framework 4, ambos os métodos usam um conjunto idêntico de caracteres de espaço em branco Unicode.

Aplica-se a

Split(String, Int32, StringSplitOptions)

Divide uma cadeia de caracteres em um número máximo de substrings baseadas em uma cadeia de caracteres delimitadora especificada e, opcionalmente, em opções.

public string[] Split (string? separator, int count, StringSplitOptions options = System.StringSplitOptions.None);
public string[] Split (string separator, int count, StringSplitOptions options = System.StringSplitOptions.None);
member this.Split : string * int * StringSplitOptions -> string[]
Public Function Split (separator As String, count As Integer, Optional options As StringSplitOptions = System.StringSplitOptions.None) As String()

Parâmetros

separator
String

Uma cadeia de caracteres que delimita as substrings nesta instância.

count
Int32

O número máximo de elementos esperados na matriz.

options
StringSplitOptions

Uma combinação bit a bit dos valores de enumeração que especifica se substrings devem ser cortadas e se substrings vazias devem ser incluídas.

Retornos

String[]

Uma matriz que contém no máximo count substrings desta instância que são delimitadas por separator.

Comentários

Se a cadeia de caracteres já tiver sido dividida count - 1 vezes, mas o final da cadeia de caracteres não tiver sido atingido, a última cadeia de caracteres na matriz retornada conterá a subcadeia de caracteres à direita restante dessa instância, intocada.

Aplica-se a

Split(String[], Int32, StringSplitOptions)

Divide uma cadeia de caracteres em um número máximo de substrings baseadas em cadeias de caracteres delimitadoras especificadas e, opcionalmente, em opções.

public:
 cli::array <System::String ^> ^ Split(cli::array <System::String ^> ^ separator, int count, StringSplitOptions options);
public string[] Split (string[] separator, int count, StringSplitOptions options);
public string[] Split (string[]? separator, int count, StringSplitOptions options);
[System.Runtime.InteropServices.ComVisible(false)]
public string[] Split (string[] separator, int count, StringSplitOptions options);
member this.Split : string[] * int * StringSplitOptions -> string[]
[<System.Runtime.InteropServices.ComVisible(false)>]
member this.Split : string[] * int * StringSplitOptions -> string[]
Public Function Split (separator As String(), count As Integer, options As StringSplitOptions) As String()

Parâmetros

separator
String[]

As cadeias de caracteres que delimitam as substrings nesta cadeia de caracteres, uma matriz vazia que não contém delimitadores ou null.

count
Int32

O número máximo de subcadeias de caracteres a serem retornadas.

options
StringSplitOptions

Uma combinação bit a bit dos valores de enumeração que especifica se substrings devem ser cortadas e se substrings vazias devem ser incluídas.

Retornos

String[]

Uma matriz cujos elementos contêm as subcadeias de caracteres desta cadeia de caracteres que são delimitadas por uma ou mais cadeias de caracteres em separator. Para obter mais informações, consulte a seção Comentários.

Atributos

Exceções

count é negativo.

options não é um dos valores StringSplitOptions.

Exemplos

O exemplo a seguir usa a StringSplitOptions enumeração para incluir ou excluir subcadeias de caracteres geradas pelo Split método .

// This example demonstrates the String.Split(Char[], Boolean) and 
//                               String.Split(Char[], Int32, Boolean) methods
using namespace System;
void Show( array<String^>^entries )
{
   Console::WriteLine( "The return value contains these {0} elements:", entries->Length );
   System::Collections::IEnumerator^ myEnum = entries->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      String^ entry = safe_cast<String^>(myEnum->Current);
      Console::Write( "<{0}>", entry );
   }

   Console::Write( "{0}{0}", Environment::NewLine );
}

int main()
{
   String^ s = ",one,,,two,,,,,three,,";
   array<Char>^sep = gcnew array<Char>{
      ','
   };
   array<String^>^result;
   
   //
   Console::WriteLine( "The original string is \"{0}\".", s );
   Console::WriteLine( "The separation character is '{0}'.", sep[ 0 ] );
   Console::WriteLine();
   
   //
   Console::WriteLine( "Split the string and return all elements:" );
   result = s->Split( sep, StringSplitOptions::None );
   Show( result );
   
   //
   Console::WriteLine( "Split the string and return all non-empty elements:" );
   result = s->Split( sep, StringSplitOptions::RemoveEmptyEntries );
   Show( result );
   
   //
   Console::WriteLine( "Split the string and return 2 elements:" );
   result = s->Split( sep, 2, StringSplitOptions::None );
   Show( result );
   
   //
   Console::WriteLine( "Split the string and return 2 non-empty elements:" );
   result = s->Split( sep, 2, StringSplitOptions::RemoveEmptyEntries );
   Show( result );
}

/*
This example produces the following results:

The original string is ",one,,,two,,,,,three,,".
The separation character is ','.

Split the string and return all elements:
The return value contains these 12 elements:
<><one><><><two><><><><><three><><>

Split the string and return all non-empty elements:
The return value contains these 3 elements:
<one><two><three>

Split the string and return 2 elements:
The return value contains these 2 elements:
<><one,,,two,,,,,three,,>

Split the string and return 2 non-empty elements:
The return value contains these 2 elements:
<one><,,two,,,,,three,,>

*/
// This example demonstrates the String.Split() methods that use
// the StringSplitOptions enumeration.
string s1 = ",ONE,,TWO,,,THREE,,";
string s2 = "[stop]" +
            "ONE[stop][stop]" +
            "TWO[stop][stop][stop]" +
            "THREE[stop][stop]";
char[] charSeparators = new char[] { ',' };
string[] stringSeparators = new string[] { "[stop]" };
string[] result;
// ------------------------------------------------------------------------------
// Split a string delimited by characters.
// ------------------------------------------------------------------------------
Console.WriteLine("1) Split a string delimited by characters:\n");

// Display the original string and delimiter characters.
Console.WriteLine($"1a) The original string is \"{s1}\".");
Console.WriteLine($"The delimiter character is '{charSeparators[0]}'.\n");

// Split a string delimited by characters and return all elements.
Console.WriteLine("1b) Split a string delimited by characters and " +
                  "return all elements:");
result = s1.Split(charSeparators, StringSplitOptions.None);
Show(result);

// Split a string delimited by characters and return all non-empty elements.
Console.WriteLine("1c) Split a string delimited by characters and " +
                  "return all non-empty elements:");
result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);
Show(result);

// Split the original string into the string and empty string before the
// delimiter and the remainder of the original string after the delimiter.
Console.WriteLine("1d) Split a string delimited by characters and " +
                  "return 2 elements:");
result = s1.Split(charSeparators, 2, StringSplitOptions.None);
Show(result);

// Split the original string into the string after the delimiter and the
// remainder of the original string after the delimiter.
Console.WriteLine("1e) Split a string delimited by characters and " +
                  "return 2 non-empty elements:");
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries);
Show(result);

// ------------------------------------------------------------------------------
// Split a string delimited by another string.
// ------------------------------------------------------------------------------
Console.WriteLine("2) Split a string delimited by another string:\n");

// Display the original string and delimiter string.
Console.WriteLine($"2a) The original string is \"{s2}\".");
Console.WriteLine($"The delimiter string is \"{stringSeparators[0]}\".\n");

// Split a string delimited by another string and return all elements.
Console.WriteLine("2b) Split a string delimited by another string and " +
                  "return all elements:");
result = s2.Split(stringSeparators, StringSplitOptions.None);
Show(result);

// Split the original string at the delimiter and return all non-empty elements.
Console.WriteLine("2c) Split a string delimited by another string and " +
                  "return all non-empty elements:");
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);
Show(result);

// Split the original string into the empty string before the
// delimiter and the remainder of the original string after the delimiter.
Console.WriteLine("2d) Split a string delimited by another string and " +
                  "return 2 elements:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.None);
Show(result);

// Split the original string into the string after the delimiter and the
// remainder of the original string after the delimiter.
Console.WriteLine("2e) Split a string delimited by another string and " +
                  "return 2 non-empty elements:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries);
Show(result);

// Display the array of separated strings using a local function
void Show(string[] entries)
{
    Console.WriteLine($"The return value contains these {entries.Length} elements:");
    foreach (string entry in entries)
    {
        Console.Write($"<{entry}>");
    }
    Console.Write("\n\n");
}

/*
This example produces the following results:

1) Split a string delimited by characters:

1a) The original string is ",ONE,,TWO,,,THREE,,".
The delimiter character is ','.

1b) Split a string delimited by characters and return all elements:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>

1c) Split a string delimited by characters and return all non-empty elements:
The return value contains these 3 elements:
<ONE><TWO><THREE>

1d) Split a string delimited by characters and return 2 elements:
The return value contains these 2 elements:
<><ONE,,TWO,,,THREE,,>

1e) Split a string delimited by characters and return 2 non-empty elements:
The return value contains these 2 elements:
<ONE><TWO,,,THREE,,>

2) Split a string delimited by another string:

2a) The original string is "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".
The delimiter string is "[stop]".

2b) Split a string delimited by another string and return all elements:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>

2c) Split a string delimited by another string and return all non-empty elements:
The return value contains these 3 elements:
<ONE><TWO><THREE>

2d) Split a string delimited by another string and return 2 elements:
The return value contains these 2 elements:
<><ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]>

2e) Split a string delimited by another string and return 2 non-empty elements:
The return value contains these 2 elements:
<ONE><TWO[stop][stop][stop]THREE[stop][stop]>

*/
// This example demonstrates the String.Split() methods that use
// the StringSplitOptions enumeration.
 
// Display the array of separated strings using a local function
let show  (entries: string[]) =
    printfn $"The return value contains these {entries.Length} elements:"
    for entry in entries do
        printf $"<{entry}>"
    printf "\n\n"

let s1 = ",ONE,,TWO,,,THREE,,"
let s2 = "[stop]" +
         "ONE[stop][stop]" +
         "TWO[stop][stop][stop]" +
         "THREE[stop][stop]"
let charSeparators = [| ',' |]
let stringSeparators = [| "[stop]" |]
// ------------------------------------------------------------------------------
// Split a string delimited by characters.
// ------------------------------------------------------------------------------
printfn "1) Split a string delimited by characters:\n"

// Display the original string and delimiter characters.
printfn $"1a) The original string is \"{s1}\"."
printfn $"The delimiter character is '{charSeparators[0]}'.\n"

// Split a string delimited by characters and return all elements.
printfn "1b) Split a string delimited by characters and return all elements:"
let result = s1.Split(charSeparators, StringSplitOptions.None)
show result

// Split a string delimited by characters and return all non-empty elements.
printfn "1c) Split a string delimited by characters and return all non-empty elements:"
let result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries)
show result

// Split the original string into the string and empty string before the
// delimiter and the remainder of the original string after the delimiter.
printfn "1d) Split a string delimited by characters and return 2 elements:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.None)
show result

// Split the original string into the string after the delimiter and the
// remainder of the original string after the delimiter.
printfn "1e) Split a string delimited by characters and return 2 non-empty elements:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
show result

// ------------------------------------------------------------------------------
// Split a string delimited by another string.
// ------------------------------------------------------------------------------
printfn "2) Split a string delimited by another string:\n"

// Display the original string and delimiter string.
printfn $"2a) The original string is \"{s2}\"."
printfn $"The delimiter string is \"{stringSeparators[0]}\".\n"

// Split a string delimited by another string and return all elements.
printfn "2b) Split a string delimited by another string and return all elements:"
let result = s2.Split(stringSeparators, StringSplitOptions.None)
show result

// Split the original string at the delimiter and return all non-empty elements.
printfn "2c) Split a string delimited by another string and return all non-empty elements:"
let result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)
show result

// Split the original string into the empty string before the
// delimiter and the remainder of the original string after the delimiter.
printfn "2d) Split a string delimited by another string and return 2 elements:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.None)
show result

// Split the original string into the string after the delimiter and the
// remainder of the original string after the delimiter.
printfn "2e) Split a string delimited by another string and return 2 non-empty elements:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
show result

(*
This example produces the following results:

1) Split a string delimited by characters:

1a) The original string is ",ONE,,TWO,,,THREE,,".
The delimiter character is ','.

1b) Split a string delimited by characters and return all elements:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>

1c) Split a string delimited by characters and return all non-empty elements:
The return value contains these 3 elements:
<ONE><TWO><THREE>

1d) Split a string delimited by characters and return 2 elements:
The return value contains these 2 elements:
<><ONE,,TWO,,,THREE,,>

1e) Split a string delimited by characters and return 2 non-empty elements:
The return value contains these 2 elements:
<ONE><TWO,,,THREE,,>

2) Split a string delimited by another string:

2a) The original string is "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".
The delimiter string is "[stop]".

2b) Split a string delimited by another string and return all elements:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>

2c) Split a string delimited by another string and return all non-empty elements:
The return value contains these 3 elements:
<ONE><TWO><THREE>

2d) Split a string delimited by another string and return 2 elements:
The return value contains these 2 elements:
<><ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]>

2e) Split a string delimited by another string and return 2 non-empty elements:
The return value contains these 2 elements:
<ONE><TWO[stop][stop][stop]THREE[stop][stop]>

*)
    Dim s1 As String = ",ONE,,TWO,,,THREE,,"
    Dim s2 As String = "[stop]" &
                       "ONE[stop][stop]" &
                       "TWO[stop][stop][stop]" &
                       "THREE[stop][stop]"
    Dim charSeparators() As Char = {","c}
    Dim stringSeparators() As String = {"[stop]"}
    Dim result() As String
    ' ------------------------------------------------------------------------------
    ' Split a string delimited by characters.
    ' ------------------------------------------------------------------------------
    Console.WriteLine("1) Split a string delimited by characters:" & vbCrLf)

    ' Display the original string and delimiter characters.
    Console.WriteLine("1a) The original string is ""{0}"".", s1)
    Console.WriteLine("The delimiter character is '{0}'." & vbCrLf, charSeparators(0))

    ' Split a string delimited by characters and return all elements.
    Console.WriteLine("1b) Split a string delimited by characters and " &
                      "return all elements:")
    result = s1.Split(charSeparators, StringSplitOptions.None)
    Show(result)

    ' Split a string delimited by characters and return all non-empty elements.
    Console.WriteLine("1c) Split a string delimited by characters and " &
                      "return all non-empty elements:")
    result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries)
    Show(result)

    ' Split the original string into the string and empty string before the 
    ' delimiter and the remainder of the original string after the delimiter.
    Console.WriteLine("1d) Split a string delimited by characters and " &
                      "return 2 elements:")
    result = s1.Split(charSeparators, 2, StringSplitOptions.None)
    Show(result)

    ' Split the original string into the string after the delimiter and the 
    ' remainder of the original string after the delimiter.
    Console.WriteLine("1e) Split a string delimited by characters and " &
                      "return 2 non-empty elements:")
    result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
    Show(result)

    ' ------------------------------------------------------------------------------
    ' Split a string delimited by another string.
    ' ------------------------------------------------------------------------------
    Console.WriteLine("2) Split a string delimited by another string:" & vbCrLf)

    ' Display the original string and delimiter string.
    Console.WriteLine("2a) The original string is ""{0}"".", s2)
    Console.WriteLine("The delimiter string is ""{0}""." & vbCrLf, stringSeparators(0))

    ' Split a string delimited by another string and return all elements.
    Console.WriteLine("2b) Split a string delimited by another string and " &
                      "return all elements:")
    result = s2.Split(stringSeparators, StringSplitOptions.None)
    Show(result)

    ' Split the original string at the delimiter and return all non-empty elements.
    Console.WriteLine("2c) Split a string delimited by another string and " &
                      "return all non-empty elements:")
    result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)
    Show(result)

    ' Split the original string into the empty string before the 
    ' delimiter and the remainder of the original string after the delimiter.
    Console.WriteLine("2d) Split a string delimited by another string and " &
                      "return 2 elements:")
    result = s2.Split(stringSeparators, 2, StringSplitOptions.None)
    Show(result)

    ' Split the original string into the string after the delimiter and the 
    ' remainder of the original string after the delimiter.
    Console.WriteLine("2e) Split a string delimited by another string and " &
                      "return 2 non-empty elements:")
    result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
    Show(result)

End Sub


' Display the array of separated strings.
Public Shared Sub Show(ByVal entries() As String)
    Console.WriteLine("The return value contains these {0} elements:", entries.Length)
    Dim entry As String
    For Each entry In entries
        Console.Write("<{0}>", entry)
    Next entry
    Console.Write(vbCrLf & vbCrLf)

End Sub

'This example produces the following results:
'
'1) Split a string delimited by characters:
'
'1a) The original string is ",ONE,,TWO,,,THREE,,".
'The delimiter character is ','.
'
'1b) Split a string delimited by characters and return all elements:
'The return value contains these 9 elements:
'<><ONE><><TWO><><><THREE><><>
'
'1c) Split a string delimited by characters and return all non-empty elements:
'The return value contains these 3 elements:
'<ONE><TWO><THREE>
'
'1d) Split a string delimited by characters and return 2 elements:
'The return value contains these 2 elements:
'<><ONE,,TWO,,,THREE,,>
'
'1e) Split a string delimited by characters and return 2 non-empty elements:
'The return value contains these 2 elements:
'<ONE><TWO,,,THREE,,>
'
'2) Split a string delimited by another string:
'
'2a) The original string is "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".
'The delimiter string is "[stop]".
'
'2b) Split a string delimited by another string and return all elements:
'The return value contains these 9 elements:
'<><ONE><><TWO><><><THREE><><>
'
'2c) Split a string delimited by another string and return all non-empty elements:
'The return value contains these 3 elements:
'<ONE><TWO><THREE>
'
'2d) Split a string delimited by another string and return 2 elements:
'The return value contains these 2 elements:
'<><ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]>
'
'2e) Split a string delimited by another string and return 2 non-empty elements:
'The return value contains these 2 elements:
'<ONE><TWO[stop][stop][stop]THREE[stop][stop]>
'

Comentários

As cadeias de caracteres delimitador não são incluídas nos elementos da matriz retornada.

Se essa instância não contiver nenhuma das cadeias de caracteres em separatorou se o count parâmetro for 1, a matriz retornada consistirá em um único elemento que contém essa instância.

Caso o parâmetro separator seja null ou não contenha nenhum caractere, os caracteres de espaço em branco devem ser considerados os delimitadores. Os caracteres de espaço em branco são definidos pelo padrão Unicode e o Char.IsWhiteSpace método retorna true se eles são passados para ele.

Para passar null para o string[] separator parâmetro , você deve indicar o tipo do null para desambiguar a chamada de algumas outras sobrecargas, como Split(Char[], Int32, StringSplitOptions). O exemplo a seguir mostra várias maneiras para identificar sem ambiguidade essa sobrecarga.

string phrase = "The quick  brown fox";

_ = phrase.Split(default(string[]), 3, StringSplitOptions.RemoveEmptyEntries);

_ = phrase.Split((string[]?)null, 3, StringSplitOptions.RemoveEmptyEntries);

_ = phrase.Split(null as string[], 3, StringSplitOptions.RemoveEmptyEntries);
let phrase = "The quick  brown fox"

phrase.Split(Unchecked.defaultof<string[]>, 3, StringSplitOptions.RemoveEmptyEntries) |> ignore

phrase.Split(null :> string[], 3, StringSplitOptions.RemoveEmptyEntries) |> ignore

phrase.Split((null: string[]), 3, StringSplitOptions.RemoveEmptyEntries) |> ignore
Dim phrase As String = "The quick brown fox"
Dim words() As String

words = phrase.Split(TryCast(Nothing, String()), 3,
                       StringSplitOptions.RemoveEmptyEntries)

words = phrase.Split(New String() {}, 3,
                     StringSplitOptions.RemoveEmptyEntries)

Se o count parâmetro for zero ou se o options parâmetro for RemoveEmptyEntries e o comprimento dessa instância for zero, uma matriz vazia será retornada.

Cada elemento de separator define um delimitador separado que consiste em um ou mais caracteres. Caso o parâmetro options seja None e dois delimitadores sejam adjacentes ou um delimitador esteja no início ou no fim dessa instância, o elemento da matriz correspondente contém Empty.

Se houver mais de count subcadeias de caracteres nessa instância, as primeiras count subcadeias de caracteres menos 1 serão retornadas nos primeiros count elementos menos 1 do valor retornado e os caracteres restantes nessa instância serão retornados no último elemento do valor retornado.

Se count for maior que o número de subcadeias de caracteres, as subcadeias de caracteres disponíveis serão retornadas e nenhuma exceção será gerada.

A matriz separadora

Se qualquer um dos elementos em consistir em separator vários caracteres, toda a subcadeia de caracteres será considerada um delimitador. Por exemplo, se um dos elementos em separator for "10", tentar dividir a cadeia de caracteres "This10is10a10string". retornará esta matriz de quatro elementos: { "This", "is", "a", "string". }.

Detalhes da comparação

O Split método extrai as subcadeias de caracteres nessa cadeia de caracteres delimitadas por uma ou mais das cadeias de caracteres no separator parâmetro e retorna essas subcadeias de caracteres como elementos de uma matriz.

O Split método procura delimitadores executando comparações usando regras de classificação ordinal que diferenciam maiúsculas de minúsculas. Para obter mais informações sobre classificações de palavra, cadeia de caracteres e ordinais, consulte a System.Globalization.CompareOptions enumeração .

O Split método ignora qualquer elemento de separator cujo valor é null ou a cadeia de caracteres vazia ("").

Para evitar resultados ambíguos quando as cadeias de caracteres em separator têm caracteres em comum, o Split método prossegue do início até o final do valor da instância e corresponde ao primeiro elemento em separator que é igual a um delimitador na instância. A ordem na qual as subcadeias de caracteres são encontradas na instância tem precedência sobre a ordem dos elementos em separator.

Por exemplo, considere uma instância cujo valor é "abcdef". Se o primeiro elemento em separator fosse "ef" e o segundo elemento fosse "bcde", o resultado da operação de divisão seria "a" e "f". Isso ocorre porque a subcadeia de caracteres na instância , "bcde", é encontrada e corresponde a um elemento em separator antes que a subcadeia de caracteres "f" seja encontrada.

No entanto, se o primeiro elemento de separator fosse "bcd" e o segundo elemento fosse "bc", o resultado da operação de divisão seria "a" e "ef". Isso ocorre porque "bcd" é o primeiro delimitador em separator que corresponde a um delimitador na instância. Se a ordem dos separadores foi invertida para que o primeiro elemento fosse "bc" e o segundo elemento fosse "bcd", o resultado seria "a" e "def".

Considerações sobre o desempenho

Os métodos Split alocam memória para o objeto de matriz retornado e um objeto String para cada elemento da matriz. Caso o aplicativo exija desempenho ideal ou em caso de gerenciamento da alocação da memória ser importante no aplicativo, considere o uso do método IndexOf ou IndexOfAny, e opcionalmente o método de Compare para localizar uma subcadeia de caracteres dentro de uma cadeia de caracteres.

Caso você esteja dividindo uma cadeia de caracteres em um separador de caractere, use o método IndexOf ou IndexOfAny para localizar um caractere separador na cadeia de caracteres. Caso você esteja dividindo uma cadeia de caracteres em uma cadeia de caracteres separadora, use o método IndexOf ou de IndexOfAny para localizar o primeiro caractere da cadeia de caracteres separadora. Em seguida, use o método Compare para determinar se os caracteres depois desse primeiro caractere são iguais aos caracteres restantes da cadeia de caracteres separadora.

Além disso, caso o mesmo conjunto de caracteres seja usado para dividir cadeias de caracteres em várias chamadas de método Split, considere criar uma matriz única e referencie-a em cada chamada de método. Isso reduz significativamente a sobrecarga adicional de cada chamada de método.

Notas aos Chamadores

No .NET Framework 3.5 e versões anteriores, se o Split(Char[]) método for passado um separator que seja null ou não contenha caracteres, o método usará um conjunto ligeiramente diferente de caracteres de espaço em branco para dividir a cadeia de caracteres do que o Trim(Char[]) método faz para cortar a cadeia de caracteres. Começando com .NET Framework 4, ambos os métodos usam um conjunto idêntico de caracteres de espaço em branco Unicode.

Aplica-se a