String.Split Método

Definición

Devuelve una matriz de cadenas que contiene las subcadenas de esta instancia que están delimitadas por elementos de la matriz de cadenas o caracteres Unicode especificada.Returns a string array that contains the substrings in this instance that are delimited by elements of a specified string or Unicode character array.

Sobrecargas

Split(Char[], Int32, StringSplitOptions)

Divide una cadena en un número máximo de subcadenas en función de los caracteres de delimitación especificados y, opcionalmente, las opciones especificadas.Splits a string into a maximum number of substrings based on specified delimiting characters and, optionally, options.

Split(Char, Int32, StringSplitOptions)

Divide una cadena en un número máximo de subcadenas en función de un carácter de delimitación especificado y, opcionalmente, las opciones especificadas.Splits a string into a maximum number of substrings based on a specified delimiting character and, optionally, options. Divide una cadena en un número máximo de subcadenas en función del separador de caracteres proporcionado y ofrece la opción de omitir las subcadenas vacías del resultado.Splits a string into a maximum number of substrings based on the provided character separator, optionally omitting empty substrings from the result.

Split(String[], Int32, StringSplitOptions)

Divide una cadena en un número máximo de subcadenas en función de las cadenas de delimitación especificadas y, opcionalmente, las opciones especificadas.Splits a string into a maximum number of substrings based on specified delimiting strings and, optionally, options.

Split(String[], StringSplitOptions)

Divide una cadena en subcadenas en función de una cadena de delimitación especificada y, opcionalmente, las opciones especificadas.Splits a string into substrings based on a specified delimiting string and, optionally, options.

Split(String, Int32, StringSplitOptions)

Divide una cadena en un número máximo de subcadenas en función de una cadena de delimitación especificada y, opcionalmente, las opciones especificadas.Splits a string into a maximum number of substrings based on a specified delimiting string and, optionally, options.

Split(Char[], StringSplitOptions)

Divide una cadena en subcadenas en función de las opciones y los caracteres de delimitación especificados.Splits a string into substrings based on specified delimiting characters and options.

Split(Char[], Int32)

Divide una cadena en un número máximo de subcadenas en función de los caracteres de delimitación especificados.Splits a string into a maximum number of substrings based on specified delimiting characters.

Split(Char, StringSplitOptions)

Divide una cadena en subcadenas en función de un carácter de delimitación especificado y, opcionalmente, las opciones especificadas.Splits a string into substrings based on a specified delimiting character and, optionally, options.

Split(String, StringSplitOptions)

Divide una cadena en subcadenas que se basan en el separador de cadena proporcionado.Splits a string into substrings that are based on the provided string separator.

Split(Char[])

Divide una cadena en subcadenas en función de los caracteres de delimitación especificados.Splits a string into substrings based on specified delimiting characters.

Comentarios

Split se utiliza para dividir una cadena delimitada en subcadenas.Split is used to break a delimited string into substrings. Puede usar una matriz de caracteres o una matriz de cadenas para especificar cero o más caracteres delimitadores o cadenas.You can use either a character array or a string array to specify zero or more delimiting characters or strings. Si no se especifica ningún carácter delimitador, la cadena se divide en caracteres de espacio en blanco.If no delimiting characters are specified, the string is split at white-space characters.

Las sobrecargas del Split método permiten limitar el número de subcadenas devueltas por el método (el Split(Char[], Int32) método), para especificar si se deben incluir las cadenas vacías y/o recortar las subcadenas en el resultado (los Split(Char[], StringSplitOptions) Split(String[], StringSplitOptions) métodos y), o para hacer ambos (los Split(Char[], Int32, StringSplitOptions) Split(String[], Int32, StringSplitOptions) métodos y).Overloads of the Split method allow you to limit the number of substrings returned by the method (the Split(Char[], Int32) method), to specify whether to include empty strings and/or trim substrings in the result (the Split(Char[], StringSplitOptions) and Split(String[], StringSplitOptions) methods), or to do both (the Split(Char[], Int32, StringSplitOptions) and Split(String[], Int32, StringSplitOptions) methods).

Sugerencia

El Split método no es siempre la mejor manera de dividir una cadena delimitada en subcadenas.The Split method is not always the best way to break a delimited string into substrings. Si no desea extraer todas las subcadenas de una cadena delimitada, o si desea analizar una cadena basándose en un patrón en lugar de en un conjunto de caracteres delimitadores, considere la posibilidad de usar expresiones regulares o combinar uno de los métodos de búsqueda que devuelve el índice de un carácter con el Substring método.If you don't want to extract all of the substrings of a delimited string, or if you want to parse a string based on a pattern instead of a set of delimiter characters, consider using regular expressions, or combine one of the search methods that returns the index of a character with the Substring method. Para obtener más información, vea extraer subcadenas de una cadena.For more information, see Extract substrings from a string.

EjemploExample

En los siguientes ejemplos se muestran tres sobrecargas diferentes de String.Split().The following examples show three different overloads of String.Split(). En el primer ejemplo se llama a la Split(Char[]) sobrecarga y se pasa un delimitador único.The first example calls the Split(Char[]) overload and passes in a single delimiter.

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.
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.

Como puede ver, los caracteres de punto (.) se incluyen en dos de las subcadenas.As you can see, the period characters (.) are included in two of the substrings. Si desea excluir los caracteres de punto, puede agregar el carácter de punto como un carácter delimitador adicional.If you want to exclude the period characters, you can add the period character as an additional delimiting character. En el ejemplo siguiente se muestra cómo hacerlo.The next example shows how to do this.

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:
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:

Los puntos desaparecen de las subcadenas, pero ahora se han incluido dos subcadenas vacías adicionales.The periods are gone from the substrings, but now two extra empty substrings have been included. Esta subcadena vacía representa la subcadena entre una palabra y el punto que la sigue.These empty substring represent the substring between a word and the period that follows it. Para omitir las subcadenas vacías de la matriz resultante, puede llamar a la sobrecarga Split(Char[], StringSplitOptions) y especificar StringSplitOptions.RemoveEmptyEntries para el parámetro options.To omit empty substrings from the resulting array, you can call the Split(Char[], StringSplitOptions) overload and specify StringSplitOptions.RemoveEmptyEntries for the options parameter.

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
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

Las secciones de las sobrecargas individuales de String.Split() contienen más ejemplos.The sections for the individual overloads of String.Split() contain further examples.

Split(Char[], Int32, StringSplitOptions)

Divide una cadena en un número máximo de subcadenas en función de los caracteres de delimitación especificados y, opcionalmente, las opciones especificadas.Splits a string into a maximum number of substrings based on specified delimiting characters and, optionally, options.

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[]

Matriz de caracteres que delimitan las subcadenas de esta cadena, una matriz vacía sin delimitadores o null.An array of characters that delimit the substrings in this string, an empty array that contains no delimiters, or null.

count
Int32

Número máximo de subcadenas que se van devolver.The maximum number of substrings to return.

options
StringSplitOptions

Combinación bit a bit de los valores de enumeración que especifica si se deben recortar las subcadenas e incluir subcadenas vacías.A bitwise combination of the enumeration values that specifies whether to trim substrings and include empty substrings.

Devoluciones

String[]

Matriz que contiene las subcadenas de esta cadena que están delimitadas por uno o varios caracteres de separator.An array that contains the substrings in this string that are delimited by one or more characters in separator. Para obtener más información, vea la sección Comentarios.For more information, see the Remarks section.

Atributos

Excepciones

count es negativo.count is negative.

options no es uno de los valores de StringSplitOptions.options is not one of the StringSplitOptions values.

Ejemplos

En el ejemplo siguiente se usa la StringSplitOptions enumeración para incluir o excluir subcadenas generadas por el Split método.The following example uses the StringSplitOptions enumeration to include or exclude substrings generated by the Split method.

// 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]>

*/
    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]>
'

Comentarios

Los caracteres delimitadores no se incluyen en los elementos de la matriz devuelta.Delimiter characters are not included in the elements of the returned array.

Si esta instancia no contiene ninguno de los caracteres de separator , o el count parámetro es 1, la matriz devuelta consta de un único elemento que contiene esta instancia.If this instance does not contain any of the characters in separator, or the count parameter is 1, the returned array consists of a single element that contains this instance.

Si el separator parámetro es null o no contiene caracteres, se supone que los caracteres de espacio en blanco son los delimitadores.If the separator parameter is null or contains no characters, white-space characters are assumed to be the delimiters. El estándar Unicode define los caracteres de espacio en blanco y el Char.IsWhiteSpace método devuelve true si se le pasan.White-space characters are defined by the Unicode standard and the Char.IsWhiteSpace method returns true if they are passed to it.

Para pasar null el char[] separator parámetro, debe indicar el tipo de null para eliminar la ambigüedad de la llamada de otras sobrecargas, como Split(String[], Int32, StringSplitOptions) .To pass null for the char[] separator parameter, you must indicate the type of the null to disambiguate the call from some other overloads, such as Split(String[], Int32, StringSplitOptions). En el ejemplo siguiente se muestran varias maneras de identificar esta sobrecarga de forma inequívoca.The following example shows several ways to unambiguously identify this overload.

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);
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)

Si el count parámetro es cero, o el options parámetro es RemoveEmptyEntries y la longitud de esta instancia es cero, se devuelve una matriz vacía.If the count parameter is zero, or the options parameter is RemoveEmptyEntries and the length of this instance is zero, an empty array is returned.

Cada elemento de separator define un carácter delimitador independiente.Each element of separator defines a separate delimiter character. Si el options parámetro es None , y dos delimitadores son adyacentes o se encuentra un delimitador al principio o al final de esta instancia, el elemento de la matriz correspondiente contiene Empty .If the options parameter is None, and two delimiters are adjacent or a delimiter is found at the beginning or end of this instance, the corresponding array element contains Empty.

Si hay más de count subcadenas en esta instancia, count se devuelven las primeras menos 1 subcadenas en los count primeros menos 1 elementos del valor devuelto, y el resto de los caracteres de esta instancia se devuelven en el último elemento del valor devuelto.If there are more than count substrings in this instance, the first count minus 1 substrings are returned in the first count minus 1 elements of the return value, and the remaining characters in this instance are returned in the last element of the return value.

Si count es mayor que el número de subcadenas, se devuelven las subcadenas disponibles y no se produce ninguna excepción.If count is greater than the number of substrings, the available substrings are returned and no exception is thrown.

Consideraciones sobre el rendimientoPerformance considerations

Los Split métodos asignan memoria para el objeto de matriz devuelto y un String objeto para cada elemento de la matriz.The Split methods allocate memory for the returned array object and a String object for each array element. Si la aplicación requiere un rendimiento óptimo o si la administración de la asignación de memoria es fundamental en la aplicación, considere la posibilidad de usar el IndexOf IndexOfAny método o y, opcionalmente Compare , el método para buscar una subcadena en una cadena.If your application requires optimal performance or if managing memory allocation is critical in your application, consider using the IndexOf or IndexOfAny method, and optionally the Compare method, to locate a substring within a string.

Si está dividiendo una cadena en un carácter separador, utilice el IndexOf IndexOfAny método o para buscar un carácter separador en la cadena.If you are splitting a string at a separator character, use the IndexOf or IndexOfAny method to locate a separator character in the string. Si está dividiendo una cadena en una cadena separadora, use el IndexOf IndexOfAny método o para buscar el primer carácter de la cadena separadora.If you are splitting a string at a separator string, use the IndexOf or IndexOfAny method to locate the first character of the separator string. A continuación, use el Compare método para determinar si los caracteres situados después del primer carácter son iguales que los caracteres restantes de la cadena separadora.Then use the Compare method to determine whether the characters after that first character are equal to the remaining characters of the separator string.

Además, si se usa el mismo conjunto de caracteres para dividir cadenas en varias Split llamadas a métodos, considere la posibilidad de crear una sola matriz y hacer referencia a ella en cada llamada al método.In addition, if the same set of characters is used to split strings in multiple Split method calls, consider creating a single array and referencing it in each method call. Esto reduce significativamente la sobrecarga adicional de cada llamada al método.This significantly reduces the additional overhead of each method call.

Notas a los autores de las llamadas

En .NET Framework 3,5 y versiones anteriores, si Split(Char[]) se pasa al método un separator que es null o no contiene ningún carácter, el método usa un conjunto ligeramente diferente de caracteres de espacio en blanco para dividir la cadena que el Trim(Char[]) método para recortar la cadena.In .NET Framework 3.5 and earlier versions, if the Split(Char[]) method is passed a separator that is null or contains no characters, the method uses a slightly different set of white-space characters to split the string than the Trim(Char[]) method does to trim the string. A partir de .NET Framework 4, ambos métodos usan un conjunto idéntico de caracteres de espacio en blanco Unicode.Starting with .NET Framework 4, both methods use an identical set of Unicode white-space characters.

Se aplica a

Split(Char, Int32, StringSplitOptions)

Divide una cadena en un número máximo de subcadenas en función de un carácter de delimitación especificado y, opcionalmente, las opciones especificadas.Splits a string into a maximum number of substrings based on a specified delimiting character and, optionally, options. Divide una cadena en un número máximo de subcadenas en función del separador de caracteres proporcionado y ofrece la opción de omitir las subcadenas vacías del resultado.Splits a string into a maximum number of substrings based on the provided character separator, optionally omitting empty substrings from the result.

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

Un carácter que delimita las subcadenas de esta instancia.A character that delimits the substrings in this instance.

count
Int32

El número máximo de elementos que se esperan en la matriz.The maximum number of elements expected in the array.

options
StringSplitOptions

Combinación bit a bit de los valores de enumeración que especifica si se deben recortar las subcadenas e incluir subcadenas vacías.A bitwise combination of the enumeration values that specifies whether to trim substrings and include empty substrings.

Devoluciones

String[]

Matriz que contiene como máximo count subcadenas de esta instancia que están delimitadas por separator.An array that contains at most count substrings from this instance that are delimited by separator.

Comentarios

Si la cadena ya se ha dividido count en 1 veces, pero no se ha alcanzado el final de la cadena, la última cadena de la matriz devuelta contendrá la subcadena final restante de esta instancia, sin tocar.If the string has already been split count - 1 times, but the end of the string has not been reached, then the last string in the returned array will contain this instance's remaining trailing substring, untouched.

Se aplica a

Split(String[], Int32, StringSplitOptions)

Divide una cadena en un número máximo de subcadenas en función de las cadenas de delimitación especificadas y, opcionalmente, las opciones especificadas.Splits a string into a maximum number of substrings based on specified delimiting strings and, optionally, options.

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[]

Las cadenas que delimitan las subcadenas de esta cadena, una matriz vacía sin delimitadores o null.The strings that delimit the substrings in this string, an empty array that contains no delimiters, or null.

count
Int32

Número máximo de subcadenas que se van devolver.The maximum number of substrings to return.

options
StringSplitOptions

Combinación bit a bit de los valores de enumeración que especifica si se deben recortar las subcadenas e incluir subcadenas vacías.A bitwise combination of the enumeration values that specifies whether to trim substrings and include empty substrings.

Devoluciones

String[]

Una matriz cuyos elementos contienen las subcadenas de esta cadena que están delimitadas por una o varias cadenas de separator.An array whose elements contain the substrings in this string that are delimited by one or more strings in separator. Para obtener más información, vea la sección Comentarios.For more information, see the Remarks section.

Atributos

Excepciones

count es negativo.count is negative.

options no es uno de los valores de StringSplitOptions.options is not one of the StringSplitOptions values.

Ejemplos

En el ejemplo siguiente se usa la StringSplitOptions enumeración para incluir o excluir subcadenas generadas por el Split método.The following example uses the StringSplitOptions enumeration to include or exclude substrings generated by the Split method.

// 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]>

*/
    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]>
'

Comentarios

Las cadenas de delimitador no se incluyen en los elementos de la matriz devuelta.Delimiter strings are not included in the elements of the returned array.

Si esta instancia no contiene ninguna de las cadenas de separator , o el count parámetro es 1, la matriz devuelta consta de un único elemento que contiene esta instancia.If this instance does not contain any of the strings in separator, or the count parameter is 1, the returned array consists of a single element that contains this instance.

Si el separator parámetro es null o no contiene caracteres, se supone que los caracteres de espacio en blanco son los delimitadores.If the separator parameter is null or contains no characters, white-space characters are assumed to be the delimiters. El estándar Unicode define los caracteres de espacio en blanco y el Char.IsWhiteSpace método devuelve true si se le pasan.White-space characters are defined by the Unicode standard and the Char.IsWhiteSpace method returns true if they are passed to it.

Para pasar null el string[] separator parámetro, debe indicar el tipo de null para eliminar la ambigüedad de la llamada de otras sobrecargas, como Split(Char[], Int32, StringSplitOptions) .To pass null for the string[] separator parameter, you must indicate the type of the null to disambiguate the call from some other overloads, such as Split(Char[], Int32, StringSplitOptions). En el ejemplo siguiente se muestran varias maneras de identificar esta sobrecarga de forma inequívoca.The following example shows several ways to unambiguously identify this overload.

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);
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)

Si el count parámetro es cero, o el options parámetro es RemoveEmptyEntries y la longitud de esta instancia es cero, se devuelve una matriz vacía.If the count parameter is zero, or the options parameter is RemoveEmptyEntries and the length of this instance is zero, an empty array is returned.

Cada elemento de separator define un delimitador independiente que consta de uno o más caracteres.Each element of separator defines a separate delimiter that consists of one or more characters. Si el options parámetro es None , y dos delimitadores son adyacentes o se encuentra un delimitador al principio o al final de esta instancia, el elemento de la matriz correspondiente contiene Empty .If the options parameter is None, and two delimiters are adjacent or a delimiter is found at the beginning or end of this instance, the corresponding array element contains Empty.

Si hay más de count subcadenas en esta instancia, count se devuelven las primeras menos 1 subcadenas en los count primeros menos 1 elementos del valor devuelto, y el resto de los caracteres de esta instancia se devuelven en el último elemento del valor devuelto.If there are more than count substrings in this instance, the first count minus 1 substrings are returned in the first count minus 1 elements of the return value, and the remaining characters in this instance are returned in the last element of the return value.

Si count es mayor que el número de subcadenas, se devuelven las subcadenas disponibles y no se produce ninguna excepción.If count is greater than the number of substrings, the available substrings are returned and no exception is thrown.

La matriz de separadorThe separator array

Si alguno de los elementos de separator consta de varios caracteres, la subcadena completa se considera un delimitador.If any of the elements in separator consists of multiple characters, the entire substring is considered a delimiter. Por ejemplo, si uno de los elementos de separator es "10", se intenta dividir la cadena "This10is10a10string".For example, if one of the elements in separator is "10", attempting to split the string "This10is10a10string." devuelve esta matriz de cuatro elementos: {"this", "is", "a", "String".returns this four-element array: { "This", "is", "a", "string." }.}.

Detalles de comparaciónComparison details

El Split método extrae las subcadenas de esta cadena que están delimitadas por una o varias de las cadenas del separator parámetro, y devuelve esas subcadenas como elementos de una matriz.The Split method extracts the substrings in this string that are delimited by one or more of the strings in the separator parameter, and returns those substrings as elements of an array.

El Split método busca delimitadores realizando comparaciones mediante reglas de ordenación ordinal con distinción entre mayúsculas y minúsculas.The Split method looks for delimiters by performing comparisons using case-sensitive ordinal sort rules. Para obtener más información sobre las ordenaciones de palabras, cadenas y ordinales, vea la System.Globalization.CompareOptions enumeración.For more information about word, string, and ordinal sorts, see the System.Globalization.CompareOptions enumeration.

El Split método omite cualquier elemento separator cuyo valor sea o una null cadena vacía ("").The Split method ignores any element of separator whose value is null or the empty string ("").

Para evitar resultados ambiguos cuando las cadenas de separator tienen caracteres en común, el Split método pasa desde el principio hasta el final del valor de la instancia de y coincide con el primer elemento de separator que es igual a un delimitador de la instancia.To avoid ambiguous results when strings in separator have characters in common, the Split method proceeds from the beginning to the end of the value of the instance, and matches the first element in separator that is equal to a delimiter in the instance. El orden en que se encuentran las subcadenas en la instancia tiene prioridad sobre el orden de los elementos de separator .The order in which substrings are encountered in the instance takes precedence over the order of elements in separator.

Por ejemplo, considere una instancia cuyo valor es "abcdef".For example, consider an instance whose value is "abcdef". Si el primer elemento de separator era "EF" y el segundo elemento era "bcde", el resultado de la operación de división sería "a" y "f".If the first element in separator was "ef" and the second element was "bcde", the result of the split operation would be "a" and "f". Esto se debe a que la subcadena de la instancia, "bcde", se encuentra y coincide con un elemento de separator antes de que se encuentre la subcadena "f".This is because the substring in the instance, "bcde", is encountered and matches an element in separator before the substring "f" is encountered.

Sin embargo, si el primer elemento de separator era "BCD" y el segundo elemento era "BC", el resultado de la operación de división sería "a" y "EF".However, if the first element of separator was "bcd" and the second element was "bc", the result of the split operation would be "a" and "ef". Esto se debe a que "BCD" es el primer delimitador de separator que coincide con un delimitador en la instancia.This is because "bcd" is the first delimiter in separator that matches a delimiter in the instance. Si se invirtió el orden de los separadores, por lo que el primer elemento era "BC" y el segundo elemento era "BCD", el resultado sería "a" y "def".If the order of the separators was reversed so the first element was "bc" and the second element was "bcd", the result would be "a" and "def".

Consideraciones de rendimientoPerformance considerations

Los Split métodos asignan memoria para el objeto de matriz devuelto y un String objeto para cada elemento de la matriz.The Split methods allocate memory for the returned array object and a String object for each array element. Si la aplicación requiere un rendimiento óptimo o si la administración de la asignación de memoria es fundamental en la aplicación, considere la posibilidad de usar el IndexOf IndexOfAny método o y, opcionalmente Compare , el método para buscar una subcadena en una cadena.If your application requires optimal performance or if managing memory allocation is critical in your application, consider using the IndexOf or IndexOfAny method, and optionally the Compare method, to locate a substring within a string.

Si está dividiendo una cadena en un carácter separador, utilice el IndexOf IndexOfAny método o para buscar un carácter separador en la cadena.If you are splitting a string at a separator character, use the IndexOf or IndexOfAny method to locate a separator character in the string. Si está dividiendo una cadena en una cadena separadora, use el IndexOf IndexOfAny método o para buscar el primer carácter de la cadena separadora.If you are splitting a string at a separator string, use the IndexOf or IndexOfAny method to locate the first character of the separator string. A continuación, use el Compare método para determinar si los caracteres situados después del primer carácter son iguales que los caracteres restantes de la cadena separadora.Then use the Compare method to determine whether the characters after that first character are equal to the remaining characters of the separator string.

Además, si se usa el mismo conjunto de caracteres para dividir cadenas en varias Split llamadas a métodos, considere la posibilidad de crear una sola matriz y hacer referencia a ella en cada llamada al método.In addition, if the same set of characters is used to split strings in multiple Split method calls, consider creating a single array and referencing it in each method call. Esto reduce significativamente la sobrecarga adicional de cada llamada al método.This significantly reduces the additional overhead of each method call.

Notas a los autores de las llamadas

En .NET Framework 3,5 y versiones anteriores, si Split(Char[]) se pasa al método un separator que es null o no contiene ningún carácter, el método usa un conjunto ligeramente diferente de caracteres de espacio en blanco para dividir la cadena que el Trim(Char[]) método para recortar la cadena.In .NET Framework 3.5 and earlier versions, if the Split(Char[]) method is passed a separator that is null or contains no characters, the method uses a slightly different set of white-space characters to split the string than the Trim(Char[]) method does to trim the string. A partir de .NET Framework 4, ambos métodos usan un conjunto idéntico de caracteres de espacio en blanco Unicode.Starting with .NET Framework 4, both methods use an identical set of Unicode white-space characters.

Se aplica a

Split(String[], StringSplitOptions)

Divide una cadena en subcadenas en función de una cadena de delimitación especificada y, opcionalmente, las opciones especificadas.Splits a string into substrings based on a specified delimiting string and, optionally, options.

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[]

Matriz de cadenas que delimitan las subcadenas de esta cadena, una matriz vacía sin delimitadores o null.An array of strings that delimit the substrings in this string, an empty array that contains no delimiters, or null.

options
StringSplitOptions

Combinación bit a bit de los valores de enumeración que especifica si se deben recortar las subcadenas e incluir subcadenas vacías.A bitwise combination of the enumeration values that specifies whether to trim substrings and include empty substrings.

Devoluciones

String[]

Una matriz cuyos elementos contienen las subcadenas de esta cadena que están delimitadas por una o varias cadenas de separator.An array whose elements contain the substrings in this string that are delimited by one or more strings in separator. Para obtener más información, vea la sección Comentarios.For more information, see the Remarks section.

Atributos

Excepciones

options no es uno de los valores de StringSplitOptions.options is not one of the StringSplitOptions values.

Ejemplos

En el ejemplo siguiente se muestra la diferencia en las matrices devueltas llamando al método de una cadena String.Split(String[], StringSplitOptions) con su options parámetro igual a StringSplitOptions.None y StringSplitOptions.RemoveEmptyEntries .The following example illustrates the difference in the arrays returned by calling a string's String.Split(String[], StringSplitOptions) method with its options parameter equal to StringSplitOptions.None and 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'
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'

En el ejemplo siguiente se define una matriz de separadores que incluyen caracteres de puntuación y de espacio en blanco.The following example defines an array of separators that include punctuation and white-space characters. Pasar esta matriz junto con un valor de StringSplitOptions.RemoveEmptyEntries al Split(String[], StringSplitOptions) método devuelve una matriz que consta de las palabras individuales de la cadena.Passing this array along with a value of StringSplitOptions.RemoveEmptyEntries to the Split(String[], StringSplitOptions) method returns an array that consists of the individual words from the string.

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
    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

Tenga en cuenta que se llama al método con el options argumento establecido en StringSplitOptions.RemoveEmptyEntries .Note that the method is called with the options argument set to StringSplitOptions.RemoveEmptyEntries. Esto evita que la matriz devuelta incluya String.Empty valores que representan coincidencias de subcadena vacías entre signos de puntuación y caracteres de espacio en blanco.This prevents the returned array from including String.Empty values that represent empty substring matches between punctuation marks and white-space characters.

Comentarios

Cuando una cadena está delimitada por un conjunto de cadenas conocido, puede utilizar el Split método para separarlo en subcadenas.When a string is delimited by a known set of strings, you can use the Split method to separate it into substrings.

Las cadenas de delimitador no se incluyen en los elementos de la matriz devuelta.Delimiter strings are not included in the elements of the returned array. Por ejemplo, si la separator matriz incluye la cadena "--" y el valor de la instancia de cadena actual es "AA--BB--CC", el método devuelve una matriz que contiene tres elementos: "AA", "BB" y "CC".For example, if the separator array includes the string "--" and the value of the current string instance is "aa--bb--cc", the method returns an array that contains three elements: "aa", "bb", and "cc".

Si esta instancia no contiene ninguna de las cadenas de separator , la matriz devuelta consta de un único elemento que contiene esta instancia.If this instance does not contain any of the strings in separator, the returned array consists of a single element that contains this instance.

Si el options parámetro es RemoveEmptyEntries y la longitud de esta instancia es cero, el método devuelve una matriz vacía.If the options parameter is RemoveEmptyEntries and the length of this instance is zero, the method returns an empty array.

Cada elemento de separator define un delimitador independiente que consta de uno o más caracteres.Each element of separator defines a separate delimiter that consists of one or more characters. Si el options argumento es None , y dos delimitadores son adyacentes o se encuentra un delimitador al principio o al final de esta instancia, el elemento de la matriz correspondiente contiene String.Empty .If the options argument is None, and two delimiters are adjacent or a delimiter is found at the beginning or end of this instance, the corresponding array element contains String.Empty. Por ejemplo, si separator incluye dos elementos, "-" y " _ ", el valor de la instancia de cadena es "- _ AA- _ " y el valor del options argumento es None , el método devuelve una matriz de cadenas con los cinco elementos siguientes:For example, if separator includes two elements, "-" and "_", the value of the string instance is "-_aa-_", and the value of the options argument is None, the method returns a string array with the following five elements:

  1. String.Empty, que representa la cadena vacía que precede a la subcadena "-" en el índice 0.String.Empty, which represents the empty string that precedes the "-" substring at index 0.

  2. String.Empty, que representa la cadena vacía entre la subcadena "-" en el índice 0 y la subcadena "" en el índice 1.String.Empty, which represents the empty string between the "-" substring at index 0 and the "" substring at index 1.

  3. "AA"."aa".

  4. String.Empty, que representa la cadena vacía que sigue a la subcadena "-" en el índice 4.String.Empty, which represents the empty string that follows the "-" substring at index 4.

  5. String.Empty, que representa la cadena vacía que sigue a la subcadena "" en el índice 5.String.Empty, which represents the empty string that follows the "" substring at index 5.

La matriz de separadorThe separator array

Si alguno de los elementos de separator consta de varios caracteres, la subcadena completa se considera un delimitador.If any of the elements in separator consists of multiple characters, the entire substring is considered a delimiter. Por ejemplo, si uno de los elementos de separator es "10", se intenta dividir la cadena "This10is10a10string".For example, if one of the elements in separator is "10", attempting to split the string "This10is10a10string." Devuelve la siguiente matriz de cuatro elementos: {"this", "is", "a", "String".returns the following four-element array: { "This", "is", "a", "string." }.}.

Si el separator parámetro es null o no contiene cadenas no vacías, se supone que los caracteres de espacio en blanco son los delimitadores.If the separator parameter is null or contains no non-empty strings, white-space characters are assumed to be the delimiters. El estándar Unicode define los caracteres de espacio en blanco y el Char.IsWhiteSpace método devuelve true si se le pasan.White-space characters are defined by the Unicode standard and the Char.IsWhiteSpace method returns true if they are passed to it.

Para pasar null el string[] separator parámetro, debe indicar el tipo de null para eliminar la ambigüedad de la llamada de otras sobrecargas, como Split(Char[], StringSplitOptions) .To pass null for the string[] separator parameter, you must indicate the type of the null to disambiguate the call from some other overloads, such as Split(Char[], StringSplitOptions). En el ejemplo siguiente se muestran varias maneras de identificar esta sobrecarga de forma inequívoca.The following example shows several ways to unambiguously identify this overload.

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);
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)

Detalles de comparaciónComparison details

El Split método extrae las subcadenas de esta cadena que están delimitadas por una o varias de las cadenas del separator parámetro, y devuelve esas subcadenas como elementos de una matriz.The Split method extracts the substrings in this string that are delimited by one or more of the strings in the separator parameter, and returns those substrings as elements of an array.

El Split método busca delimitadores realizando comparaciones mediante reglas de ordenación ordinal con distinción entre mayúsculas y minúsculas.The Split method looks for delimiters by performing comparisons using case-sensitive ordinal sort rules. Para obtener más información sobre las ordenaciones de palabras, cadenas y ordinales, vea la System.Globalization.CompareOptions enumeración.For more information about word, string, and ordinal sorts, see the System.Globalization.CompareOptions enumeration.

El Split método omite cualquier elemento separator cuyo valor sea o una null cadena vacía ("").The Split method ignores any element of separator whose value is null or the empty string ("").

Para evitar resultados ambiguos cuando las cadenas de separator tienen caracteres en común, la Split operación continúa desde el principio hasta el final del valor de la instancia y coincide con el primer elemento de separator que es igual a un delimitador de la instancia.To avoid ambiguous results when strings in separator have characters in common, the Split operation proceeds from the beginning to the end of the value of the instance, and matches the first element in separator that is equal to a delimiter in the instance. El orden en que se encuentran las subcadenas en la instancia tiene prioridad sobre el orden de los elementos de separator .The order in which substrings are encountered in the instance takes precedence over the order of elements in separator.

Por ejemplo, considere una instancia cuyo valor es "abcdef".For example, consider an instance whose value is "abcdef". Si el primer elemento de separator era "EF" y el segundo elemento era "bcde", el resultado de la operación de división sería una matriz de cadenas que contiene dos elementos, "a" y "f".If the first element in separator was "ef" and the second element was "bcde", the result of the split operation would be a string array that contains two elements, "a" and "f". Esto se debe a que la subcadena de la instancia, "bcde", se encuentra y coincide con un elemento de separator antes de que se encuentre la subcadena "f".This is because the substring in the instance, "bcde", is encountered and matches an element in separator before the substring "f" is encountered.

Sin embargo, si el primer elemento de separator era "BCD" y el segundo elemento era "BC", el resultado de la operación de división sería una matriz de cadenas que contiene dos elementos, "a" y "EF".However, if the first element of separator was "bcd" and the second element was "bc", the result of the split operation would be a string array that contains two elements, "a" and "ef". Esto se debe a que "BCD" es el primer delimitador de separator que coincide con un delimitador en la instancia.This is because "bcd" is the first delimiter in separator that matches a delimiter in the instance. Si se revirtió el orden de los separadores, por lo que el primer elemento era "BC" y el segundo elemento era "BCD", el resultado sería una matriz de cadenas que contiene dos elementos, "a" y "def".If the order of the separators was reversed so the first element was "bc" and the second element was "bcd", the result would be a string array that contains two elements, "a" and "def".

Consideraciones de rendimientoPerformance considerations

Los Split métodos asignan memoria para el objeto de matriz devuelto y un String objeto para cada elemento de la matriz.The Split methods allocate memory for the returned array object and a String object for each array element. Si la aplicación requiere un rendimiento óptimo o si la administración de la asignación de memoria es fundamental en la aplicación, considere la posibilidad de usar el IndexOf IndexOfAny método o y, opcionalmente Compare , el método para buscar una subcadena en una cadena.If your application requires optimal performance or if managing memory allocation is critical in your application, consider using the IndexOf or IndexOfAny method, and optionally the Compare method, to locate a substring within a string.

Si está dividiendo una cadena en un carácter separador, utilice el IndexOf IndexOfAny método o para buscar un carácter separador en la cadena.If you are splitting a string at a separator character, use the IndexOf or IndexOfAny method to locate a separator character in the string. Si está dividiendo una cadena en una cadena separadora, use el IndexOf IndexOfAny método o para buscar el primer carácter de la cadena separadora.If you are splitting a string at a separator string, use the IndexOf or IndexOfAny method to locate the first character of the separator string. A continuación, use el Compare método para determinar si los caracteres situados después del primer carácter son iguales que los caracteres restantes de la cadena separadora.Then use the Compare method to determine whether the characters after that first character are equal to the remaining characters of the separator string.

Además, si se usa el mismo conjunto de caracteres para dividir cadenas en varias Split llamadas a métodos, considere la posibilidad de crear una sola matriz y hacer referencia a ella en cada llamada al método.In addition, if the same set of characters is used to split strings in multiple Split method calls, consider creating a single array and referencing it in each method call. Esto reduce significativamente la sobrecarga adicional de cada llamada al método.This significantly reduces the additional overhead of each method call.

Notas a los autores de las llamadas

En .NET Framework 3,5 y versiones anteriores, si Split(Char[]) se pasa al método un separator que es null o no contiene ningún carácter, el método usa un conjunto ligeramente diferente de caracteres de espacio en blanco para dividir la cadena que el Trim(Char[]) método para recortar la cadena.In .NET Framework 3.5 and earlier versions, if the Split(Char[]) method is passed a separator that is null or contains no characters, the method uses a slightly different set of white-space characters to split the string than the Trim(Char[]) method does to trim the string. A partir de .NET Framework 4, ambos métodos usan un conjunto idéntico de caracteres de espacio en blanco Unicode.Starting with .NET Framework 4, both methods use an identical set of Unicode white-space characters.

Se aplica a

Split(String, Int32, StringSplitOptions)

Divide una cadena en un número máximo de subcadenas en función de una cadena de delimitación especificada y, opcionalmente, las opciones especificadas.Splits a string into a maximum number of substrings based on a specified delimiting string and, optionally, options.

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

Una cadena que delimita las subcadenas de esta instancia.A string that delimits the substrings in this instance.

count
Int32

El número máximo de elementos que se esperan en la matriz.The maximum number of elements expected in the array.

options
StringSplitOptions

Combinación bit a bit de los valores de enumeración que especifica si se deben recortar las subcadenas e incluir subcadenas vacías.A bitwise combination of the enumeration values that specifies whether to trim substrings and include empty substrings.

Devoluciones

String[]

Matriz que contiene como máximo count subcadenas de esta instancia que están delimitadas por separator.An array that contains at most count substrings from this instance that are delimited by separator.

Comentarios

Si la cadena ya se ha dividido count en 1 veces, pero no se ha alcanzado el final de la cadena, la última cadena de la matriz devuelta contendrá la subcadena final restante de esta instancia, sin tocar.If the string has already been split count - 1 times, but the end of the string has not been reached, then the last string in the returned array will contain this instance's remaining trailing substring, untouched.

Se aplica a

Split(Char[], StringSplitOptions)

Divide una cadena en subcadenas en función de las opciones y los caracteres de delimitación especificados.Splits a string into substrings based on specified delimiting characters and options.

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[]

Matriz de caracteres que delimitan las subcadenas de esta cadena, una matriz vacía sin delimitadores o null.An array of characters that delimit the substrings in this string, an empty array that contains no delimiters, or null.

options
StringSplitOptions

Combinación bit a bit de los valores de enumeración que especifica si se deben recortar las subcadenas e incluir subcadenas vacías.A bitwise combination of the enumeration values that specifies whether to trim substrings and include empty substrings.

Devoluciones

String[]

Una matriz cuyos elementos contienen las subcadenas de esta cadena que están delimitadas por uno o varios caracteres de separator.An array whose elements contain the substrings in this string that are delimited by one or more characters in separator. Para obtener más información, vea la sección Comentarios.For more information, see the Remarks section.

Atributos

Excepciones

options no es uno de los valores de StringSplitOptions.options is not one of the StringSplitOptions values.

Ejemplos

En el ejemplo siguiente se usa la StringSplitOptions enumeración para incluir o excluir subcadenas generadas por el Split método.The following example uses the StringSplitOptions enumeration to include or exclude substrings generated by the Split method.

// 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]>

*/
    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]>
'

Comentarios

Los caracteres delimitadores (los caracteres de la separator matriz) no se incluyen en los elementos de la matriz devuelta.Delimiter characters (the characters in the separator array) are not included in the elements of the returned array. Por ejemplo, si la separator matriz incluye el carácter "-" y el valor de la instancia de la cadena actual es "AA-BB-CC", el método devuelve una matriz que contiene tres elementos: "AA", "BB" y "CC".For example, if the separator array includes the character "-" and the value of the current string instance is "aa-bb-cc", the method returns an array that contains three elements: "aa", "bb", and "cc".

Si esta instancia no contiene ninguno de los caracteres de separator , la matriz devuelta consta de un único elemento que contiene esta instancia.If this instance does not contain any of the characters in separator, the returned array consists of a single element that contains this instance.

Si el options parámetro es RemoveEmptyEntries y la longitud de esta instancia es cero, el método devuelve una matriz vacía.If the options parameter is RemoveEmptyEntries and the length of this instance is zero, the method returns an empty array.

Cada elemento de separator define un delimitador independiente que consta de un único carácter.Each element of separator defines a separate delimiter that consists of a single character. Si el options argumento es None , y dos delimitadores son adyacentes o se encuentra un delimitador al principio o al final de esta instancia, el elemento de la matriz correspondiente contiene String.Empty .If the options argument is None, and two delimiters are adjacent or a delimiter is found at the beginning or end of this instance, the corresponding array element contains String.Empty. Por ejemplo, si separator incluye dos elementos, '-' y '_' , el valor de la instancia de cadena es "- _ AA- _ " y el valor del options argumento es None , el método devuelve una matriz de cadenas con los cinco elementos siguientes:For example, if separator includes two elements, '-' and '_', the value of the string instance is "-_aa-_", and the value of the options argument is None, the method returns a string array with the following five elements:

  1. String.Empty, que representa la cadena vacía que precede al carácter "-" en el índice 0.String.Empty, which represents the empty string that precedes the "-" character at index 0.

  2. String.Empty, que representa la cadena vacía entre el carácter "-" en el índice 0 y el carácter "" en el índice 1.String.Empty, which represents the empty string between the "-" character at index 0 and the "" character at index 1.

  3. "AA"."aa".

  4. String.Empty, que representa la cadena vacía que sigue al carácter "-" en el índice 4.String.Empty, which represents the empty string that follows the "-" character at index 4.

  5. String.Empty, que representa la cadena vacía que sigue al carácter "" en el índice 5.String.Empty, which represents the empty string that follows the "" character at index 5.

La matriz de separadorThe separator array

Si el separator parámetro es null o no contiene caracteres, se supone que los caracteres de espacio en blanco son los delimitadores.If the separator parameter is null or contains no characters, white-space characters are assumed to be the delimiters. El estándar Unicode define los caracteres de espacio en blanco y el Char.IsWhiteSpace método devuelve true si se le pasan.White-space characters are defined by the Unicode standard and the Char.IsWhiteSpace method returns true if they are passed to it.

Para pasar null el char[] separator parámetro, debe indicar el tipo de null para eliminar la ambigüedad de la llamada de otras sobrecargas, como Split(String[], StringSplitOptions) .To pass null for the char[] separator parameter, you must indicate the type of the null to disambiguate the call from some other overloads, such as Split(String[], StringSplitOptions). En el ejemplo siguiente se muestran varias maneras de identificar esta sobrecarga de forma inequívoca.The following example shows several ways to unambiguously identify this overload.

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);
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)

Detalles de comparaciónComparison details

El Split método extrae las subcadenas de esta cadena que están delimitadas por uno o más de los caracteres del separator parámetro, y devuelve esas subcadenas como elementos de una matriz.The Split method extracts the substrings in this string that are delimited by one or more of the characters in the separator parameter, and returns those substrings as elements of an array.

El Split método busca delimitadores realizando comparaciones mediante reglas de ordenación ordinal con distinción entre mayúsculas y minúsculas.The Split method looks for delimiters by performing comparisons using case-sensitive ordinal sort rules. Para obtener más información sobre las ordenaciones de palabras, cadenas y ordinales, vea la System.Globalization.CompareOptions enumeración.For more information about word, string, and ordinal sorts, see the System.Globalization.CompareOptions enumeration.

Consideraciones sobre el rendimientoPerformance considerations

Los Split métodos asignan memoria para el objeto de matriz devuelto y un String objeto para cada elemento de la matriz.The Split methods allocate memory for the returned array object and a String object for each array element. Si la aplicación requiere un rendimiento óptimo o si la administración de la asignación de memoria es fundamental en la aplicación, considere la posibilidad de usar el IndexOf IndexOfAny método o y, opcionalmente Compare , el método para buscar una subcadena en una cadena.If your application requires optimal performance or if managing memory allocation is critical in your application, consider using the IndexOf or IndexOfAny method, and optionally the Compare method, to locate a substring within a string.

Si está dividiendo una cadena en un carácter separador, utilice el IndexOf IndexOfAny método o para buscar un carácter separador en la cadena.If you are splitting a string at a separator character, use the IndexOf or IndexOfAny method to locate a separator character in the string. Si está dividiendo una cadena en una cadena separadora, use el IndexOf IndexOfAny método o para buscar el primer carácter de la cadena separadora.If you are splitting a string at a separator string, use the IndexOf or IndexOfAny method to locate the first character of the separator string. A continuación, use el Compare método para determinar si los caracteres situados después del primer carácter son iguales que los caracteres restantes de la cadena separadora.Then use the Compare method to determine whether the characters after that first character are equal to the remaining characters of the separator string.

Además, si se usa el mismo conjunto de caracteres para dividir cadenas en varias Split llamadas a métodos, considere la posibilidad de crear una sola matriz y hacer referencia a ella en cada llamada al método.In addition, if the same set of characters is used to split strings in multiple Split method calls, consider creating a single array and referencing it in each method call. Esto reduce significativamente la sobrecarga adicional de cada llamada al método.This significantly reduces the additional overhead of each method call.

Notas a los autores de las llamadas

En .NET Framework 3,5 y versiones anteriores, si Split(Char[]) se pasa al método un separator que es null o no contiene ningún carácter, el método usa un conjunto ligeramente diferente de caracteres de espacio en blanco para dividir la cadena que el Trim(Char[]) método para recortar la cadena.In .NET Framework 3.5 and earlier versions, if the Split(Char[]) method is passed a separator that is null or contains no characters, the method uses a slightly different set of white-space characters to split the string than the Trim(Char[]) method does to trim the string. A partir de .NET Framework 4, ambos métodos usan un conjunto idéntico de caracteres de espacio en blanco Unicode.Starting with .NET Framework 4, both methods use an identical set of Unicode white-space characters.

Se aplica a

Split(Char[], Int32)

Divide una cadena en un número máximo de subcadenas en función de los caracteres de delimitación especificados.Splits a string into a maximum number of substrings based on specified delimiting characters.

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[]

Matriz de caracteres que delimitan las subcadenas de esta cadena, una matriz vacía sin delimitadores o null.An array of characters that delimit the substrings in this string, an empty array that contains no delimiters, or null.

count
Int32

Número máximo de subcadenas que se van devolver.The maximum number of substrings to return.

Devoluciones

String[]

Una matriz cuyos elementos contienen las subcadenas de esta instancia que están delimitadas por uno o varios caracteres de separator.An array whose elements contain the substrings in this instance that are delimited by one or more characters in separator. Para obtener más información, vea la sección Comentarios.For more information, see the Remarks section.

Excepciones

count es negativo.count is negative.

Ejemplos

En el ejemplo siguiente se muestra cómo count se puede utilizar para limitar el número de cadenas devueltas por Split .The following example demonstrates how count can be used to limit the number of strings returned by 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"
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"

Comentarios

Los caracteres delimitadores no se incluyen en los elementos de la matriz devuelta.Delimiter characters are not included in the elements of the returned array.

Si esta instancia no contiene ninguno de los caracteres de separator , la matriz devuelta consta de un único elemento que contiene esta instancia.If this instance does not contain any of the characters in separator, the returned array consists of a single element that contains this instance. Si count es cero, se devuelve una matriz vacía.If count is zero, an empty array is returned.

Si el separator parámetro es null o no contiene caracteres, se supone que los caracteres de espacio en blanco son los delimitadores.If the separator parameter is null or contains no characters, white-space characters are assumed to be the delimiters. El estándar Unicode define los caracteres de espacio en blanco y el Char.IsWhiteSpace método devuelve true si se le pasan.White-space characters are defined by the Unicode standard and the Char.IsWhiteSpace method returns true if they are passed to it.

Cada elemento de separator define un carácter delimitador independiente.Each element of separator defines a separate delimiter character. Si dos delimitadores son adyacentes, o se encuentra un delimitador al principio o al final de esta instancia, el elemento de la matriz correspondiente contiene Empty .If two delimiters are adjacent, or a delimiter is found at the beginning or end of this instance, the corresponding array element contains Empty.

Si hay más de count subcadenas en esta instancia, las primeras count - 1 subcadenas se devuelven en los primeros count - 1 elementos del valor devuelto y el resto de los caracteres de esta instancia se devuelven en el último elemento del valor devuelto.If there are more than count substrings in this instance, the first count - 1 substrings are returned in the first count - 1 elements of the return value, and the remaining characters in this instance are returned in the last element of the return value.

Si count es mayor que el número de subcadenas, se devuelven las subcadenas disponibles y no se produce ninguna excepción.If count is greater than the number of substrings, the available substrings are returned and no exception is thrown.

En la tabla siguiente se muestran algunos ejemplos.The following table shows some examples.

IdiomaLanguage Valor de cadenaString value SeparadorSeparator Matriz devueltaReturned array
C#C# "42, 12, 19""42, 12, 19" New Char [] {', ', ' '}new Char[] {',', ' '} {"42", "", "12", "", "19"}{"42", "", "12", "", "19"}
Visual BasicVisual Basic "42, 12, 19""42, 12, 19" Char () = {"," c "," c})Char() = {","c, " "c}) {"42", "", "12", "", "19"}{"42", "", "12", "", "19"}
C#C# "42.. 12.. 19"."42..12..19." New Char [] {'. '}new Char[] {'.'} {"42", "", "12", "", "19", ""}{"42", "", "12", "", "19", ""}
Visual BasicVisual Basic "42.. 12.. 19"."42..12..19." Char () = {"." unidadChar() = {"."c} {"42", "", "12", "", "19", ""}{"42", "", "12", "", "19", ""}
C#C# Plátano"Banana" New Char [] {'. '}new Char[] {'.'} {"Banana"}{"Banana"}
Visual BasicVisual Basic Plátano"Banana" Char () = {"." unidadChar() = {"."c} {"Banana"}{"Banana"}
C#C# "Darb\nSmarba""Darb\nSmarba" New Char [] {}new Char[] {} {"Darb", "Smarba"}{"Darb", "Smarba"}
Visual BasicVisual Basic "Darb" & vbLf & "Smarba""Darb" & vbLf & "Smarba" Char () = {}Char() = {} {"Darb", "Smarba"}{"Darb", "Smarba"}
C#C# "Darb\nSmarba""Darb\nSmarba" nullnull {"Darb", "Smarba"}{"Darb", "Smarba"}
Visual BasicVisual Basic "Darb" & vbLf & "Smarba""Darb" & vbLf & "Smarba" NadaNothing {"Darb", "Smarba"}{"Darb", "Smarba"}

Consideraciones sobre el rendimientoPerformance considerations

Los Split métodos asignan memoria para el objeto de matriz devuelto y un String objeto para cada elemento de la matriz.The Split methods allocate memory for the returned array object and a String object for each array element. Si la aplicación requiere un rendimiento óptimo o si la administración de la asignación de memoria es fundamental en la aplicación, considere la posibilidad de usar el IndexOf IndexOfAny método o y, opcionalmente Compare , el método para buscar una subcadena en una cadena.If your application requires optimal performance or if managing memory allocation is critical in your application, consider using the IndexOf or IndexOfAny method, and optionally the Compare method, to locate a substring within a string.

Si está dividiendo una cadena en un carácter separador, utilice el IndexOf IndexOfAny método o para buscar un carácter separador en la cadena.If you are splitting a string at a separator character, use the IndexOf or IndexOfAny method to locate a separator character in the string. Si está dividiendo una cadena en una cadena separadora, use el IndexOf IndexOfAny método o para buscar el primer carácter de la cadena separadora.If you are splitting a string at a separator string, use the IndexOf or IndexOfAny method to locate the first character of the separator string. A continuación, use el Compare método para determinar si los caracteres situados después del primer carácter son iguales que los caracteres restantes de la cadena separadora.Then use the Compare method to determine whether the characters after that first character are equal to the remaining characters of the separator string.

Además, si se usa el mismo conjunto de caracteres para dividir cadenas en varias Split llamadas a métodos, considere la posibilidad de crear una sola matriz y hacer referencia a ella en cada llamada al método.In addition, if the same set of characters is used to split strings in multiple Split method calls, consider creating a single array and referencing it in each method call. Esto reduce significativamente la sobrecarga adicional de cada llamada al método.This significantly reduces the additional overhead of each method call.

Notas a los autores de las llamadas

En .NET Framework 3,5 y versiones anteriores, si Split(Char[]) se pasa al método un separator que es null o no contiene ningún carácter, el método usa un conjunto ligeramente diferente de caracteres de espacio en blanco para dividir la cadena que el Trim(Char[]) método para recortar la cadena.In .NET Framework 3.5 and earlier versions, if the Split(Char[]) method is passed a separator that is null or contains no characters, the method uses a slightly different set of white-space characters to split the string than the Trim(Char[]) method does to trim the string. A partir de .NET Framework 4, ambos métodos usan un conjunto idéntico de caracteres de espacio en blanco Unicode.Starting with .NET Framework 4, both methods use an identical set of Unicode white-space characters.

Consulte también

Se aplica a

Split(Char, StringSplitOptions)

Divide una cadena en subcadenas en función de un carácter de delimitación especificado y, opcionalmente, las opciones especificadas.Splits a string into substrings based on a specified delimiting character and, optionally, options.

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

Un carácter que delimita las subcadenas de esta cadena.A character that delimits the substrings in this string.

options
StringSplitOptions

Combinación bit a bit de los valores de enumeración que especifica si se deben recortar las subcadenas e incluir subcadenas vacías.A bitwise combination of the enumeration values that specifies whether to trim substrings and include empty substrings.

Devoluciones

String[]

Una matriz cuyos elementos contienen las subcadenas de esta instancia que están delimitadas por separator.An array whose elements contain the substrings from this instance that are delimited by separator.

Se aplica a

Split(String, StringSplitOptions)

Divide una cadena en subcadenas que se basan en el separador de cadena proporcionado.Splits a string into substrings that are based on the provided string separator.

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

Una cadena que delimita las subcadenas de esta cadena.A string that delimits the substrings in this string.

options
StringSplitOptions

Combinación bit a bit de los valores de enumeración que especifica si se deben recortar las subcadenas e incluir subcadenas vacías.A bitwise combination of the enumeration values that specifies whether to trim substrings and include empty substrings.

Devoluciones

String[]

Una matriz cuyos elementos contienen las subcadenas de esta instancia que están delimitadas por separator.An array whose elements contain the substrings from this instance that are delimited by separator.

Se aplica a

Split(Char[])

Divide una cadena en subcadenas en función de los caracteres de delimitación especificados.Splits a string into substrings based on specified delimiting characters.

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[]

Matriz de caracteres de delimitación, matriz vacía sin ningún delimitador o null.An array of delimiting characters, an empty array that contains no delimiters, or null.

Devoluciones

String[]

Una matriz cuyos elementos contienen las subcadenas de esta instancia que están delimitadas por uno o varios caracteres de separator.An array whose elements contain the substrings from this instance that are delimited by one or more characters in separator. Para obtener más información, vea la sección Comentarios.For more information, see the Remarks section.

Ejemplos

En el ejemplo siguiente se muestra cómo extraer palabras individuales de un bloque de texto tratando el carácter de espacio ( ) y el carácter de tabulación ( \t ) como delimitadores.The following example demonstrates how to extract individual words from a block of text by treating the space character ( ) and tab character (\t) as delimiters. La cadena que se está dividiendo incluye ambos caracteres.The string being split includes both of these characters.

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
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

Comentarios

Cuando una cadena está delimitada por un conjunto de caracteres conocido, puede utilizar el Split(Char[]) método para separarlo en subcadenas.When a string is delimited by a known set of characters, you can use the Split(Char[]) method to separate it into substrings.

Los caracteres delimitadores no se incluyen en los elementos de la matriz devuelta.Delimiter characters are not included in the elements of the returned array. Por ejemplo, si la matriz de separador incluye el carácter "-" y el valor de la instancia de cadena actual es "AA-BB-CC", el método devuelve una matriz que contiene tres elementos: "AA", "BB" y "CC".For example, if the separator array includes the character "-" and the value of the current string instance is "aa-bb-cc", the method returns an array that contains three elements: "aa", "bb", and "cc".

Si esta instancia no contiene ninguno de los caracteres de separator , la matriz devuelta consta de un único elemento que contiene esta instancia.If this instance does not contain any of the characters in separator, the returned array consists of a single element that contains this instance.

Cada elemento de separator define un carácter delimitador independiente.Each element of separator defines a separate delimiter character. Si dos delimitadores son adyacentes, o se encuentra un delimitador al principio o al final de esta instancia, el elemento correspondiente de la matriz devuelta contiene Empty .If two delimiters are adjacent, or a delimiter is found at the beginning or end of this instance, the corresponding element in the returned array contains Empty.

En la tabla siguiente se muestran algunos ejemplos.The following table shows some examples.

IdiomaLanguage Valor de cadenaString value SeparadorSeparator Matriz devueltaReturned array
C#C# "42, 12, 19""42, 12, 19" New Char [] {', ', ' '}new Char[] {',', ' '} {"42", "", "12", "", "19"}{"42", "", "12", "", "19"}
Visual BasicVisual Basic "42, 12, 19""42, 12, 19" Char () = {"," c "," c})Char() = {","c, " "c}) {"42", "", "12", "", "19"}{"42", "", "12", "", "19"}
C#C# "42.. 12.. 19"."42..12..19." New Char [] {'. '}new Char[] {'.'} {"42", "", "12", "", "19", ""}{"42", "", "12", "", "19", ""}
Visual BasicVisual Basic "42.. 12.. 19"."42..12..19." Char () = {"." unidadChar() = {"."c} {"42", "", "12", "", "19", ""}{"42", "", "12", "", "19", ""}
C#C# Plátano"Banana" New Char [] {'. '}new Char[] {'.'} {"Banana"}{"Banana"}
Visual BasicVisual Basic Plátano"Banana" Char () = {"." unidadChar() = {"."c} {"Banana"}{"Banana"}
C#C# "Darb\nSmarba""Darb\nSmarba" New Char [] {}new Char[] {} {"Darb", "Smarba"}{"Darb", "Smarba"}
Visual BasicVisual Basic "Darb" & vbLf & "Smarba""Darb" & vbLf & "Smarba" Char () = {}Char() = {} {"Darb", "Smarba"}{"Darb", "Smarba"}
C#C# "Darb\nSmarba""Darb\nSmarba" nullnull {"Darb", "Smarba"}{"Darb", "Smarba"}
Visual BasicVisual Basic "Darb" & vbLf & "Smarba""Darb" & vbLf & "Smarba" NadaNothing {"Darb", "Smarba"}{"Darb", "Smarba"}

La matriz de separadorThe separator array

Cada elemento del separador define un delimitador independiente que consta de un único carácter.Each element of separator defines a separate delimiter that consists of a single character.

Si el separator argumento es null o no contiene caracteres, el método trata los caracteres de espacio en blanco como delimitadores.If the separator argument is null or contains no characters, the method treats white-space characters as the delimiters. El estándar Unicode define los caracteres de espacio en blanco y el Char.IsWhiteSpace método devuelve true si se le pasa un carácter de espacio en blanco.White-space characters are defined by the Unicode standard, and the Char.IsWhiteSpace method returns true if a white-space character is passed to it.

String. Split (Char []) y resolución de sobrecarga del compiladorString.Split(Char[]) and compiler overload resolution

Aunque el único parámetro de esta sobrecarga de String.Split es una matriz de caracteres, puede llamarlo con un solo carácter, como se muestra en el ejemplo siguiente.Although the single parameter for this overload of String.Split is a character array, you can call it with a single character, as the following example shows.

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.
    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.

Dado que el separator parámetro se decora con el ParamArrayAttribute atributo, los compiladores interpretarán un único carácter como una matriz de caracteres de un solo elemento.Because the separator parameter is decorated with the ParamArrayAttribute attribute, compilers will interpret a single character as a single-element character array. Este no es el caso de otras String.Split sobrecargas que incluyen un separator parámetro; debe pasar explícitamente las sobrecargas de una matriz de caracteres como separator argumento.This is not the case for other String.Split overloads that include a separator parameter; you must explicitly pass these overloads a character array as the separator argument.

Detalles de comparaciónComparison details

El Split(Char[]) método extrae las subcadenas de esta cadena que están delimitadas por uno o varios de los caracteres de la separator matriz y devuelve esas subcadenas como elementos de una matriz.The Split(Char[]) method extracts the substrings in this string that are delimited by one or more of the characters in the separator array, and returns those substrings as elements of an array.

El Split(Char[]) método busca delimitadores realizando comparaciones mediante reglas de ordenación ordinal con distinción entre mayúsculas y minúsculas.The Split(Char[]) method looks for delimiters by performing comparisons using case-sensitive ordinal sort rules. Para obtener más información sobre las ordenaciones de palabras, cadenas y ordinales, vea la System.Globalization.CompareOptions enumeración.For more information about word, string, and ordinal sorts, see the System.Globalization.CompareOptions enumeration.

Consideraciones sobre el rendimientoPerformance considerations

Los Split métodos asignan memoria para el objeto de matriz devuelto y un String objeto para cada elemento de la matriz.The Split methods allocate memory for the returned array object and a String object for each array element. Si la aplicación requiere un rendimiento óptimo o si la administración de la asignación de memoria es fundamental en la aplicación, considere la posibilidad de usar el IndexOf IndexOfAny método o.If your application requires optimal performance or if managing memory allocation is critical in your application, consider using the IndexOf or IndexOfAny method. También tiene la opción de usar el Compare método para buscar una subcadena dentro de una cadena.You also have the option of using the Compare method to locate a substring within a string.

Para dividir una cadena en un carácter separador, utilice IndexOf el IndexOfAny método o para buscar un carácter separador en la cadena.To split a string at a separator character, use the IndexOf or IndexOfAny method to locate a separator character in the string. Para dividir una cadena en una cadena separadora, use IndexOf el IndexOfAny método o para buscar el primer carácter de la cadena separadora.To split a string at a separator string, use the IndexOf or IndexOfAny method to locate the first character of the separator string. A continuación, use el Compare método para determinar si los caracteres situados después del primer carácter son iguales que los caracteres restantes de la cadena separadora.Then use the Compare method to determine whether the characters after that first character are equal to the remaining characters of the separator string.

Además, si se usa el mismo conjunto de caracteres para dividir cadenas en varias Split llamadas a métodos, considere la posibilidad de crear una sola matriz y hacer referencia a ella en cada llamada al método.In addition, if the same set of characters is used to split strings in multiple Split method calls, consider creating a single array and referencing it in each method call. Esto reduce significativamente la sobrecarga adicional de cada llamada al método.This significantly reduces the additional overhead of each method call.

Notas a los autores de las llamadas

En .NET Framework 3,5 y versiones anteriores, si Split(Char[]) se pasa al método un separator que es null o no contiene ningún carácter, el método usa un conjunto ligeramente diferente de caracteres de espacio en blanco para dividir la cadena que el Trim(Char[]) método para recortar la cadena.In .NET Framework 3.5 and earlier versions, if the Split(Char[]) method is passed a separator that is null or contains no characters, the method uses a slightly different set of white-space characters to split the string than the Trim(Char[]) method does to trim the string. A partir de .NET Framework 4, ambos métodos usan un conjunto idéntico de caracteres de espacio en blanco Unicode.Starting with .NET Framework 4, both methods use an identical set of Unicode white-space characters.

Consulte también

Se aplica a