String.Split String.Split String.Split String.Split Method

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(String[], Int32, StringSplitOptions) Split(String[], Int32, StringSplitOptions) Split(String[], Int32, StringSplitOptions) Split(String[], Int32, StringSplitOptions)

Divide una cadena en un número máximo de subcadenas en función de las cadenas de una matriz.Splits a string into a maximum number of substrings based on the strings in an array. Puede especificar si las subcadenas incluyen elementos de matriz vacíos.You can specify whether the substrings include empty array elements.

Split(String, Int32, StringSplitOptions) Split(String, Int32, StringSplitOptions) Split(String, Int32, StringSplitOptions)
Split(Char[], Int32, StringSplitOptions) Split(Char[], Int32, StringSplitOptions) Split(Char[], Int32, StringSplitOptions) Split(Char[], Int32, StringSplitOptions)

Divide una cadena en un número máximo de subcadenas en función de los caracteres de una matriz.Splits a string into a maximum number of substrings based on the characters in an array.

Split(Char, Int32, StringSplitOptions) Split(Char, Int32, StringSplitOptions) Split(Char, Int32, StringSplitOptions)
Split(String[], StringSplitOptions) Split(String[], StringSplitOptions) Split(String[], StringSplitOptions) Split(String[], StringSplitOptions)

Divide una cadena en subcadenas en función de las cadenas de una matriz.Splits a string into substrings based on the strings in an array. Puede especificar si las subcadenas incluyen elementos de matriz vacíos.You can specify whether the substrings include empty array elements.

Split(Char, StringSplitOptions) Split(Char, StringSplitOptions) Split(Char, StringSplitOptions)
Split(Char[], StringSplitOptions) Split(Char[], StringSplitOptions) Split(Char[], StringSplitOptions) Split(Char[], StringSplitOptions)

Divide una cadena en subcadenas en función de los caracteres de una matriz.Splits a string into substrings based on the characters in an array. Puede especificar si las subcadenas incluyen elementos de matriz vacíos.You can specify whether the substrings include empty array elements.

Split(Char[], Int32) Split(Char[], Int32) Split(Char[], Int32) Split(Char[], Int32)

Divide una cadena en un número máximo de subcadenas en función de los caracteres de una matriz.Splits a string into a maximum number of substrings based on the characters in an array. Número máximo de subcadenas que se va devolver.You also specify the maximum number of substrings to return.

Split(Char[]) Split(Char[]) Split(Char[]) Split(Char[])

Divide una cadena en subcadenas basadas en los caracteres de una matriz.Splits a string into substrings that are based on the characters in an array.

Split(String, StringSplitOptions) Split(String, StringSplitOptions) Split(String, StringSplitOptions)

Comentarios

Split se usa para dividir una cadena delimitada en subcadenas.Split is used to break a delimited string into substrings. Puede usar una matriz de caracteres para especificar cero, uno o varios caracteres delimitadores (el Split(Char[]) método), o bien puede usar una matriz de caracteres para especificar cero, una o varias cadenas delimitadoras.You can use either a character array to specify zero, one, or multiple delimiting characters (the Split(Char[]) method), or you can use a character array to specify zero, one, or multiple delimiting strings. Las sobrecargas de la Split método le permiten limitar el número de subcadenas devuelto por el método (el Split(Char[], Int32) método), para determinar si las cadenas vacías se incluyen en las subcadenas devueltas (el Split(Char[], StringSplitOptions) y Split(String[], StringSplitOptions) métodos, o para realizar ambas acciones (el Split(Char[], Int32, StringSplitOptions) y Split(String[], Int32, StringSplitOptions) métodos).Overloads of the Split method allow you to limit the number of substrings returned by the method (the Split(Char[], Int32) method), to determine whether empty strings are included in the returned substrings (the Split(Char[], StringSplitOptions) and Split(String[], StringSplitOptions) methods, or to do both (the Split(Char[], Int32, StringSplitOptions) and Split(String[], Int32, StringSplitOptions) methods).

Nota

Los ejemplos de C# de este artículo se ejecutan en el ejecutor de código en línea y área de juegos de Try.NET.The C# examples in this article run in the Try.NET inline code runner and playground. Haga clic en el botón Ejecutar para ejecutar un ejemplo en una ventana interactiva.Select the Run button to run an example in an interactive window. Una vez que se ejecuta el código, puede modificar y ejecutar el código modificado si vuelve a hacer clic en Ejecutar.Once you execute the code, you can modify it and run the modified code by selecting Run again. El código modificado se ejecuta en la ventana interactiva o, si se produce un error en la compilación, en la ventana interactiva se muestran todos los mensajes de error del compilador de C#.The modified code either runs in the interactive window or, if compilation fails, the interactive window displays all C# compiler error messages.

Alternativas a String.SplitAlternatives to String.Split

El Split método no siempre es 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 según un patrón en lugar de un conjunto de caracteres delimitadores, considere las siguientes alternativas.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 the following alternatives.

Expresiones regularesRegular expressions

Si las cadenas se ajustan a un patrón fijo, puede usar una expresión regular para extraer y controlar sus elementos.If your strings conform to a fixed pattern, you can use a regular expression to extract and handle their elements. Por ejemplo, si las cadenas adoptan la forma "número operando número" puede usar un expresión regular para extraer y controlar el elementos de la cadena.For example, if strings take the form "number operand number" you can use a regular expression to extract and handle the string's elements. Por ejemplo:Here's an example:

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      String[] expressions = { "16 + 21", "31 * 3", "28 / 3",
                               "42 - 18", "12 * 7",
                               "2, 4, 6, 8" };
      String pattern = @"(\d+)\s+([-+*/])\s+(\d+)";
      foreach (var expression in expressions)
         foreach (Match m in Regex.Matches(expression, pattern)) {
            int value1 = Int32.Parse(m.Groups[1].Value);
            int value2 = Int32.Parse(m.Groups[3].Value);
            switch (m.Groups[2].Value)
            {
               case "+":
                  Console.WriteLine("{0} = {1}", m.Value, value1 + value2);
                  break;
               case "-":
                  Console.WriteLine("{0} = {1}", m.Value, value1 - value2);
                  break;
               case "*":
                  Console.WriteLine("{0} = {1}", m.Value, value1 * value2);
                  break;
               case "/":
                  Console.WriteLine("{0} = {1:N2}", m.Value, value1 / value2);
                  break;
            }
         }
   }
}
// The example displays the following output:
//       16 + 21 = 37
//       31 * 3 = 93
//       28 / 3 = 9.33
//       42 - 18 = 24
//       12 * 7 = 84
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim expressions() As String = { "16 + 21", "31 * 3", "28 / 3",
                                      "42 - 18", "12 * 7",
                                      "2, 4, 6, 8" }

      Dim pattern As String = "(\d+)\s+([-+*/])\s+(\d+)"
      For Each expression In expressions
         For Each m As Match in Regex.Matches(expression, pattern)
            Dim value1 As Integer = Int32.Parse(m.Groups(1).Value)
            Dim value2 As Integer = Int32.Parse(m.Groups(3).Value)
            Select Case m.Groups(2).Value
               Case "+"
                  Console.WriteLine("{0} = {1}", m.Value, value1 + value2)
               Case "-"
                  Console.WriteLine("{0} = {1}", m.Value, value1 - value2)
               Case "*"
                  Console.WriteLine("{0} = {1}", m.Value, value1 * value2)
               Case "/"
                  Console.WriteLine("{0} = {1:N2}", m.Value, value1 / value2)
            End Select
         Next
      Next
   End Sub
End Module
' The example displays the following output:
'       16 + 21 = 37
'       31 * 3 = 93
'       28 / 3 = 9.33
'       42 - 18 = 24
'       12 * 7 = 84

El patrón de expresión regular (\d+)\s+([-+*/])\s+(\d+) se define así:The regular expression pattern (\d+)\s+([-+*/])\s+(\d+) is defined like this:

ModeloPattern DescripciónDescription
(\d+) Buscar coincidencias con uno o más dígitos decimales.Match one or more decimal digits. Este es el primer grupo de captura.This is the first capturing group.
\s+ Coincide con uno o más caracteres de espacio en blanco.Match one or more white-space characters.
([-+*/]) Coincide con un operador aritmético de signo (+, -, *, o /).Match an arithmetic operator sign (+, -, *, or /). Este es el segundo grupo de captura.This is the second capturing group.
\s+ Coincide con uno o más caracteres de espacio en blanco.Match one or more white-space characters.
(\d+) Buscar coincidencias con uno o más dígitos decimales.Match one or more decimal digits. Éste es el tercer grupo de captura.This is the third capturing group.

También puede usar una expresión regular para extraer subcadenas de una cadena según un patrón en lugar de un conjunto fijo de caracteres.You can also use a regular expression to extract substrings from a string based on a pattern rather than a fixed set of characters. Se trata de un escenario común cuando se produce cualquiera de estas condiciones:This is a common scenario when either of these conditions occurs:

  • Uno o varios de los caracteres delimitadores no actuar siempre como un delimitador en la String instancia.One or more of the delimiter characters does not always serve as a delimiter in the String instance.

  • La secuencia y el número de caracteres de delimitador es variable o desconocido.The sequence and number of delimiter characters is variable or unknown.

Por ejemplo, el Split método no puede utilizarse para dividir la cadena siguiente, porque el número de \n (en C#) o vbCrLf (en Visual Basic) de caracteres es variable y no siempre actúan como delimitadores.For example, the Split method cannot be used to split the following string, because the number of \n (in C#) or vbCrLf (in Visual Basic) characters is variable, and they don't always serve as delimiters.

[This is captured\ntext.]\n\n[\n[This is more captured text.]\n]  
\n[Some more captured text:\n   Option1\n   Option2][Terse text.]  

Una expresión regular puede dividir fácilmente, como el siguiente ejemplo se muestra esta cadena.A regular expression can split this string easily, as the following example shows.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      String input = "[This is captured\ntext.]\n\n[\n" +
                     "[This is more captured text.]\n]\n" +
                     "[Some more captured text:\n   Option1" +
                     "\n   Option2][Terse text.]";
      String pattern = @"\[([^\[\]]+)\]";
      int ctr = 0;
      foreach (Match m in Regex.Matches(input, pattern))
         Console.WriteLine("{0}: {1}", ++ctr, m.Groups[1].Value);
   }
}
// The example displays the following output:
//       1: This is captured
//       text.
//       2: This is more captured text.
//       3: Some more captured text:
//          Option1
//          Option2
//       4: Terse text.
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim input As String = String.Format("[This is captured{0}text.]" +
                                          "{0}{0}[{0}[This is more " +
                                          "captured text.]{0}{0}" +
                                          "[Some more captured text:" +
                                          "{0}   Option1" +
                                          "{0}   Option2][Terse text.]",
                                          vbCrLf)
      Dim pattern As String = "\[([^\[\]]+)\]"
      Dim ctr As Integer = 0
      For Each m As Match In Regex.Matches(input, pattern)
         ctr += 1
         Console.WriteLine("{0}: {1}", ctr, m.Groups(1).Value)
      Next
   End Sub
End Module
' The example displays the following output:
'       1: This is captured
'       text.
'       2: This is more captured text.
'       3: Some more captured text:
'          Option1
'          Option2
'       4: Terse text.

El patrón de expresión regular \[([^\[\]]+)\] se define así:The regular expression pattern \[([^\[\]]+)\] is defined like this:

ModeloPattern DescripciónDescription
\[ Coincide con un corchete de apertura.Match an opening bracket.
([^\[\]]+) Coincide con cualquier carácter que no es una corchete de apertura o un cierre una o varias veces.Match any character that is not an opening or a closing bracket one or more times. Este es el primer grupo de captura.This is the first capturing group.
\] Coincide con un corchete de cierre.Match a closing bracket.

El Regex.Split es casi idéntico al método String.Split, excepto en que divide una cadena según un patrón de expresión regular en lugar de un juego de caracteres fijos.The Regex.Split method is almost identical to String.Split, except that it splits a string based on a regular expression pattern instead of a fixed character set. Por ejemplo, en el ejemplo siguiente se utiliza el Regex.Split método para dividir una cadena que contiene subcadenas delimitadas por varias combinaciones de guiones y otros caracteres.For example, the following example uses the Regex.Split method to split a string that contains substrings delimited by various combinations of hyphens and other characters.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      String input = "abacus -- alabaster - * - atrium -+- " +
                     "any -*- actual - + - armoir - - alarm";
      String pattern = @"\s-\s?[+*]?\s?-\s";
      String[] elements = Regex.Split(input, pattern);
      foreach (var element in elements)
         Console.WriteLine(element);
   }
}
// The example displays the following output:
//       abacus
//       alabaster
//       atrium
//       any
//       actual
//       armoir
//       alarm
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim input As String = "abacus -- alabaster - * - atrium -+- " +
                            "any -*- actual - + - armoir - - alarm"
      Dim pattern As String = "\s-\s?[+*]?\s?-\s"
      Dim elements() As String = Regex.Split(input, pattern)
      For Each element In elements
         Console.WriteLine(element)
      Next
   End Sub
End Module
' The example displays the following output:
'       abacus
'       alabaster
'       atrium
'       any
'       actual
'       armoir
'       alarm

El patrón de expresión regular \s-\s?[+*]?\s?-\s se define así:The regular expression pattern \s-\s?[+*]?\s?-\s is defined like this:

ModeloPattern DescripciónDescription
\s- Coincide con un carácter de espacio en blanco seguido por un guión.Match a white-space character followed by a hyphen.
\s? Busca coincidencias con cero o un carácter de espacio en blanco.Match zero or one white-space character.
[+*]? Coincide con cero o una aparición de uno de ellos la + o * caracteres.Match zero or one occurrence of either the + or * character.
\s? Busca coincidencias con cero o un carácter de espacio en blanco.Match zero or one white-space character.
-\s Coincide con un guión seguido de un carácter de espacio en blanco.Match a hyphen followed by a white-space character.

Los métodos de búsqueda y Substring (método)Search methods and the Substring method

Si no está interesado en todas las subcadenas de una cadena, prefiere trabajar con uno de los métodos de comparación de cadenas que devuelve el índice donde comienza la coincidencia.If you aren't interested in all of the substrings in a string, you might prefer to work with one of the string comparison methods that returns the index at which the match begins. A continuación, puede llamar a la Substring método para extraer la subcadena que desee.You can then call the Substring method to extract the substring that you want. Los métodos de comparación de cadenas incluyen:The string comparison methods include:

  • IndexOf, que devuelve el índice de base cero de la primera aparición de un carácter o cadena en una instancia de cadena.IndexOf, which returns the zero-based index of the first occurrence of a character or string in a string instance.

  • IndexOfAny, que devuelve el índice de base cero de la instancia actual de la cadena de la primera aparición de un carácter de una matriz de caracteres.IndexOfAny, which returns the zero-based index in the current string instance of the first occurrence of any character in a character array.

  • LastIndexOf, que devuelve el índice de base cero de la última aparición de un carácter o cadena en una instancia de cadena.LastIndexOf, which returns the zero-based index of the last occurrence of a character or string in a string instance.

  • LastIndexOfAny, que devuelve un índice de base cero de la instancia actual de la cadena de la última aparición de un carácter de una matriz de caracteres.LastIndexOfAny, which returns a zero-based index in the current string instance of the last occurrence of any character in a character array.

En el ejemplo siguiente se usa el IndexOf método para buscar los períodos en una cadena.The following example uses the IndexOf method to find the periods in a string. A continuación, usa el Substring método para devolver las oraciones completas.It then uses the Substring method to return full sentences.

using System;
using System.Collections.Generic;

public class Example
{
   public static void Main()
   {
      String value = "This is the first sentence in a string. " +
                     "More sentences will follow. For example, " +
                     "this is the third sentence. This is the " +
                     "fourth. And this is the fifth and final " +
                     "sentence.";
      var sentences = new List<String>();
      int position = 0;
      int start = 0;
      // Extract sentences from the string.
      do {
         position = value.IndexOf('.', start);
         if (position >= 0) {
            sentences.Add(value.Substring(start, position - start + 1).Trim());
            start = position + 1;
         }
      } while (position > 0);

      // Display the sentences.
      foreach (var sentence in sentences)
         Console.WriteLine(sentence);
   }
}
// The example displays the following output:
//       This is the first sentence in a string.
//       More sentences will follow.
//       For example, this is the third sentence.
//       This is the fourth.
//       And this is the fifth and final sentence.
Imports System.Collections.Generic

Module Example
   Public Sub Main()
      Dim value As String = "This is the first sentence in a string. " +
                            "More sentences will follow. For example, " +
                            "this is the third sentence. This is the " +
                            "fourth. And this is the fifth and final " +
                            "sentence."
      Dim sentences As New List(Of String)
      Dim position As Integer = 0
      Dim start As Integer = 0
      ' Extract sentences from the string.
      Do
         position = value.IndexOf("."c, start)
         If position >= 0 Then
            sentences.Add(value.Substring(start, position - start + 1).Trim())
            start = position + 1
         End If
      Loop While position > 0
      
      ' Display the sentences.
      For Each sentence In sentences
         Console.WriteLine(sentence)
      Next
   End Sub
End Module
' The example displays the following output:
'       This is the first sentence in a string.
'       More sentences will follow.
'       For example, this is the third sentence.
'       This is the fourth.
'       And this is the fifth and final sentence.

Split(String[], Int32, StringSplitOptions) Split(String[], Int32, StringSplitOptions) Split(String[], Int32, StringSplitOptions) Split(String[], Int32, StringSplitOptions)

Divide una cadena en un número máximo de subcadenas en función de las cadenas de una matriz.Splits a string into a maximum number of substrings based on the strings in an array. Puede especificar si las subcadenas incluyen elementos de matriz vacíos.You can specify whether the substrings include empty array elements.

public:
 cli::array <System::String ^> ^ Split(cli::array <System::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[]
Public Function Split (separator As String(), count As Integer, 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.A string array that delimits the substrings in this string, an empty array that contains no delimiters, or null.

count
Int32 Int32 Int32 Int32

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

options
StringSplitOptions StringSplitOptions StringSplitOptions StringSplitOptions

RemoveEmptyEntries para omitir los elementos de matriz vacíos de la matriz devuelta; o bien, None para incluir los elementos de matriz vacíos en la matriz devuelta.RemoveEmptyEntries to omit empty array elements from the array returned; or None to include empty array elements in the array returned.

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.

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 el StringSplitOptions enumeración para incluir o excluir las 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() methods that use
// the StringSplitOptions enumeration.
using System;

class Sample 
{
    public static void Main() 
    {
    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 \"{0}\".", s1);
    Console.WriteLine("The delimiter character is '{0}'.\n", 
                       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:\n");

// Display the original string and delimiter string.
    Console.WriteLine("2a) The original string is \"{0}\".", s2);
    Console.WriteLine("The delimiter string is \"{0}\".\n", 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);
    }

// Display the array of separated strings.
    public static void Show(string[] entries)
    {
    Console.WriteLine("The return value contains these {0} elements:", entries.Length);
    foreach (string entry in entries)
        {
        Console.Write("<{0}>", entry);
        }
    Console.Write("\n\n");
    }
}
/*
This example produces the following results:

1) Split a string delimited by characters:

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

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

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

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

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

2) Split a string delimited by another string:

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

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

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

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

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

*/

' This example demonstrates the String() methods that use
' the StringSplitOptions enumeration.
Imports System

Class Sample
    Public Shared Sub Main() 
        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 'Main
    
    
    ' 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 'Show
End Class 'Sample
'
'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

Detalles de valor devueltoReturn value details

Las cadenas delimitadoras 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 del parámetro es 1, la matriz devuelta consta de un solo 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, caracteres de espacio en blanco se supone que los delimitadores.If the separator parameter is null or contains no characters, white-space characters are assumed to be the delimiters. Caracteres de espacio en blanco se definen mediante Unicode estándar y devuelven true si se pasan a la Char.IsWhiteSpace método.White-space characters are defined by the Unicode standard and return true if they are passed to the Char.IsWhiteSpace method. Sin embargo, si la separator parámetro en la llamada a esta sobrecarga del método es null, se produce un error en la resolución de sobrecarga del compilador.However, if the separator parameter in the call to this method overload is null, compiler overload resolution fails. Para identificar de forma inequívoca el método llamado, el código debe indicar el tipo de la null.To unambiguously identify the called method, your code must indicate the type of the null. El ejemplo siguiente muestra varias maneras para identificar inequívocamente esta sobrecarga.The following example shows several ways to unambiguously identify this overload.

string phrase = "The quick  brown fox";
string[] words;

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

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

words = 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 la 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 Noney dos delimitadores son adyacentes o se encuentra un delimitador al principio o al final de esta instancia, el elemento correspondiente de la matriz 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 de esta instancia, la primera count menos 1 subcadenas se devuelven en la primera count menos 1 elementos del valor devuelto y los caracteres restantes de esta instancia se devuelven en los últimos 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 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, toda la subcadena 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", 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 la comparaciónComparison details

El Split método extrae las subcadenas de esta cadena que están delimitadas por una o varias de las cadenas en el 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 realizar comparaciones usando las reglas de ordenación ordinal 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 acerca de la ordenación de palabras, cadena y ordinal, vea el 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 de separator cuyo valor es null o una 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 en separator tienen caracteres en común, el Split continúa desde el principio hasta el final del valor de la instancia de método y coincide con el primer elemento de separator que es igual a un delimitador de la instancia de.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 el que se encuentran las subcadenas en la instancia tiene prioridad sobre el orden de los elementos en separator.The order in which substrings are encountered in the instance takes precedence over the order of elements in separator.

Por ejemplo, considere la posibilidad de 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 es "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 es porque la subcadena en la instancia de "bcde", se encuentra y coincide con un elemento en separator antes de que se encuentra 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 es "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 es porque "bcd" es el primer delimitador en 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 invierte el orden de los separadores, por lo que el primer elemento es "bc" y el segundo elemento es "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 sobre el rendimientoPerformance considerations

El Split métodos asignan memoria para el objeto de matriz devuelto y un String objeto para cada elemento de 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 administrar la asignación de memoria es fundamental en la aplicación, considere el uso de la IndexOf o IndexOfAny método y opcionalmente el Compare método para localizar una subcadena dentro de 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 va a dividir una cadena en un carácter separador, utilice el IndexOf o IndexOfAny método 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 va a dividir una cadena en una cadena separadora, utilice el IndexOf o IndexOfAny método 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, utilice el Compare método para determinar si los caracteres después de ese primer carácter son iguales a 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 el mismo conjunto de caracteres se utiliza para dividir las cadenas en varios 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 considerablemente 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 el .NET Framework 3,5.NET Framework 3.5 y versiones anteriores, si la Split(Char[]) se pasa al método un separator decir null o no contiene ningún carácter, el método usa un conjunto de caracteres ligeramente diferentes para dividir la cadena que el Trim(Char[]) hace el método para recorta la cadena.In the .NET Framework 3,5.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 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 de Unicode.Starting with the .NET Framework 4, both methods use an identical set of Unicode white-space characters.

Split(String, Int32, StringSplitOptions) Split(String, Int32, StringSplitOptions) Split(String, Int32, StringSplitOptions)

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

Devoluciones

String[]

Split(Char[], Int32, StringSplitOptions) Split(Char[], Int32, StringSplitOptions) Split(Char[], Int32, StringSplitOptions) Split(Char[], Int32, StringSplitOptions)

Divide una cadena en un número máximo de subcadenas en función de los caracteres de una matriz.Splits a string into a maximum number of substrings based on the characters in an array.

public:
 cli::array <System::String ^> ^ Split(cli::array <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[]
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.A character array that delimits the substrings in this string, an empty array that contains no delimiters, or null.

count
Int32 Int32 Int32 Int32

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

options
StringSplitOptions StringSplitOptions StringSplitOptions StringSplitOptions

RemoveEmptyEntries para omitir los elementos de matriz vacíos de la matriz devuelta; o bien, None para incluir los elementos de matriz vacíos en la matriz devuelta.RemoveEmptyEntries to omit empty array elements from the array returned; or None to include empty array elements in the array returned.

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.

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 el StringSplitOptions enumeración para incluir o excluir las 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() methods that use
// the StringSplitOptions enumeration.
using System;

class Sample 
{
    public static void Main() 
    {
    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 \"{0}\".", s1);
    Console.WriteLine("The delimiter character is '{0}'.\n", 
                       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:\n");

// Display the original string and delimiter string.
    Console.WriteLine("2a) The original string is \"{0}\".", s2);
    Console.WriteLine("The delimiter string is \"{0}\".\n", 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);
    }

// Display the array of separated strings.
    public static void Show(string[] entries)
    {
    Console.WriteLine("The return value contains these {0} elements:", entries.Length);
    foreach (string entry in entries)
        {
        Console.Write("<{0}>", entry);
        }
    Console.Write("\n\n");
    }
}
/*
This example produces the following results:

1) Split a string delimited by characters:

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

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

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

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

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

2) Split a string delimited by another string:

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

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

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

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

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

*/

' This example demonstrates the String() methods that use
' the StringSplitOptions enumeration.
Imports System

Class Sample
    Public Shared Sub Main() 
        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 'Main
    
    
    ' 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 'Show
End Class 'Sample
'
'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

No se incluyen los caracteres delimitadores 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 en separator, o el count del parámetro es 1, la matriz devuelta consta de un solo 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, caracteres de espacio en blanco se supone que los delimitadores.If the separator parameter is null or contains no characters, white-space characters are assumed to be the delimiters. Caracteres de espacio en blanco se definen mediante Unicode estándar y devuelven true si se pasan a la Char.IsWhiteSpace método.White-space characters are defined by the Unicode standard and return true if they are passed to the Char.IsWhiteSpace method. Sin embargo, si la separator parámetro en la llamada a esta sobrecarga del método es null, se produce un error en la resolución de sobrecarga del compilador.However, if the separator parameter in the call to this method overload is null, compiler overload resolution fails. Para identificar de forma inequívoca el método llamado, el código debe indicar el tipo del valor null.To unambiguously identify the called method, your code must indicate the type of the null. El ejemplo siguiente muestra varias maneras para identificar inequívocamente esta sobrecarga.The following example shows several ways to unambiguously identify this overload.

string phrase = "The quick  brown fox";
string[] words;

words = phrase.Split(default(Char[]), 3, StringSplitOptions.RemoveEmptyEntries);

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

words = 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 la 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 Noney dos delimitadores son adyacentes o se encuentra un delimitador al principio o al final de esta instancia, el elemento correspondiente de la matriz 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 de esta instancia, la primera count menos 1 subcadenas se devuelven en la primera count menos 1 elementos del valor devuelto y los caracteres restantes de esta instancia se devuelven en los últimos 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 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

El Split métodos asignan memoria para el objeto de matriz devuelto y un String objeto para cada elemento de 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 administrar la asignación de memoria es fundamental en la aplicación, considere el uso de la IndexOf o IndexOfAny método y opcionalmente el Compare método para localizar una subcadena dentro de 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 va a dividir una cadena en un carácter separador, utilice el IndexOf o IndexOfAny método 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 va a dividir una cadena en una cadena separadora, utilice el IndexOf o IndexOfAny método 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, utilice el Compare método para determinar si los caracteres después de ese primer carácter son iguales a 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 el mismo conjunto de caracteres se utiliza para dividir las cadenas en varios 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 considerablemente 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 el .NET Framework 3,5.NET Framework 3.5 y versiones anteriores, si la Split(Char[]) se pasa al método un separator decir null o no contiene ningún carácter, el método usa un conjunto de caracteres ligeramente diferentes para dividir la cadena que el Trim(Char[]) hace el método para recorta la cadena.In the .NET Framework 3,5.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 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 de Unicode.Starting with the .NET Framework 4, both methods use an identical set of Unicode white-space characters.

Split(Char, Int32, StringSplitOptions) Split(Char, Int32, StringSplitOptions) Split(Char, Int32, StringSplitOptions)

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

Devoluciones

String[]

Split(String[], StringSplitOptions) Split(String[], StringSplitOptions) Split(String[], StringSplitOptions) Split(String[], StringSplitOptions)

Divide una cadena en subcadenas en función de las cadenas de una matriz.Splits a string into substrings based on the strings in an array. Puede especificar si las subcadenas incluyen elementos de matriz vacíos.You can specify whether the substrings include empty array elements.

public:
 cli::array <System::String ^> ^ Split(cli::array <System::String ^> ^ separator, StringSplitOptions options);
[System.Runtime.InteropServices.ComVisible(false)]
public string[] Split (string[] separator, StringSplitOptions options);
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.A string array that delimits the substrings in this string, an empty array that contains no delimiters, or null.

options
StringSplitOptions StringSplitOptions StringSplitOptions StringSplitOptions

RemoveEmptyEntries para omitir los elementos de matriz vacíos de la matriz devuelta; o bien, None para incluir los elementos de matriz vacíos en la matriz devuelta.RemoveEmptyEntries to omit empty array elements from the array returned; or None to include empty array elements in the array returned.

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.

Excepciones

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

Ejemplos

El ejemplo siguiente ilustra la diferencia entre las matrices devueltas por una llamada a una cadena String.Split(String[], StringSplitOptions) método con su options igual al parámetro 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.

using System;

class Example 
{
   public static void Main() 
   {
      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   \"{0}\".", source);
      Console.WriteLine();
      Console.WriteLine("Using the delimiter string:\n   \"{0}\"", 
                        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("   ");
      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 ({0} elements):", 
                        result.Length);
      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'
Module Example
   Public Sub Main()
      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()
   End Sub
End Module
' 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'

El ejemplo siguiente define una matriz de separadores que incluyen signos de puntuación y caracteres de espacio en blanco.The following example defines an array of separators that include punctuation and white-space characters. Si se pasa esta matriz junto con un valor de StringSplitOptions.RemoveEmptyEntries a la 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.

using System;

public class Example
{
   public static void Main()
   {
      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
Module Example
   Public Sub Main()
      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
End Module
' 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 establecido en StringSplitOptions.RemoveEmptyEntries.Note that the method is called with the options argument set to StringSplitOptions.RemoveEmptyEntries. Esto impide que la matriz devuelta incluya String.Empty valores que representan las coincidencias de subcadena vacía 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 conocido de cadenas, puede usar 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.

Detalles de valor devueltoReturn value details

Las cadenas delimitadoras 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 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 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 solo 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 Noney dos delimitadores son adyacentes o se encuentra un delimitador al principio o al final de esta instancia, el elemento correspondiente de la matriz 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 de la options argumento es None, el método devuelve una matriz de cadenas con los siguientes cinco elementos: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 sting 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 al í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, toda la subcadena 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", 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 caracteres, caracteres de espacio en blanco se supone que los delimitadores.If the separator parameter is null or contains no characters, white-space characters are assumed to be the delimiters. Caracteres de espacio en blanco se definen mediante Unicode estándar y devuelven true si se pasan a la Char.IsWhiteSpace método.White-space characters are defined by the Unicode standard and return true if they are passed to the Char.IsWhiteSpace method.

Si el separator parámetro en la llamada a esta sobrecarga del método es null, se produce un error en la resolución de sobrecarga del compilador.If the separator parameter in the call to this method overload is null, compiler overload resolution fails. Para identificar de forma inequívoca el método llamado, el código debe indicar el tipo de la null.To unambiguously identify the called method, your code must indicate the type of the null. El ejemplo siguiente muestra varias maneras para identificar inequívocamente esta sobrecarga.The following example shows several ways to unambiguously identify this overload.

string phrase = "The quick  brown fox";
string[] words;

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

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

words = 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 la comparaciónComparison details

El Split método extrae las subcadenas de esta cadena que están delimitadas por una o varias de las cadenas en el 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 realizar comparaciones usando las reglas de ordenación ordinal 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 acerca de la ordenación de palabras, cadena y ordinal, vea el 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 de separator cuyo valor es null o una 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 en separator tienen caracteres en común, el 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 de.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 el que se encuentran las subcadenas en la instancia tiene prioridad sobre el orden de los elementos en separator.The order in which substrings are encountered in the instance takes precedence over the order of elements in separator.

Por ejemplo, considere la posibilidad de 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 es "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 es porque la subcadena en la instancia de "bcde", se encuentra y coincide con un elemento en separator antes de que se encuentra 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 es "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 es porque "bcd" es el primer delimitador en 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 invierte el orden de los separadores, por lo que el primer elemento es "bc" y el segundo elemento es "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 sobre el rendimientoPerformance considerations

El Split métodos asignan memoria para el objeto de matriz devuelto y un String objeto para cada elemento de 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 administrar la asignación de memoria es fundamental en la aplicación, considere el uso de la IndexOf o IndexOfAny método y opcionalmente el Compare método para localizar una subcadena dentro de 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 va a dividir una cadena en un carácter separador, utilice el IndexOf o IndexOfAny método 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 va a dividir una cadena en una cadena separadora, utilice el IndexOf o IndexOfAny método 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, utilice el Compare método para determinar si los caracteres después de ese primer carácter son iguales a 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 el mismo conjunto de caracteres se utiliza para dividir las cadenas en varios 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 considerablemente 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 el .NET Framework 3,5.NET Framework 3.5 y versiones anteriores, si la Split(Char[]) se pasa al método un separator decir null o no contiene ningún carácter, el método usa un conjunto de caracteres ligeramente diferentes para dividir la cadena que el Trim(Char[]) hace el método para recorta la cadena.In the .NET Framework 3,5.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 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 de Unicode.Starting with the .NET Framework 4, both methods use an identical set of Unicode white-space characters.

Split(Char, StringSplitOptions) Split(Char, StringSplitOptions) Split(Char, StringSplitOptions)

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

Devoluciones

String[]

Split(Char[], StringSplitOptions) Split(Char[], StringSplitOptions) Split(Char[], StringSplitOptions) Split(Char[], StringSplitOptions)

Divide una cadena en subcadenas en función de los caracteres de una matriz.Splits a string into substrings based on the characters in an array. Puede especificar si las subcadenas incluyen elementos de matriz vacíos.You can specify whether the substrings include empty array elements.

public:
 cli::array <System::String ^> ^ Split(cli::array <char> ^ separator, StringSplitOptions options);
[System.Runtime.InteropServices.ComVisible(false)]
public string[] Split (char[] separator, StringSplitOptions options);
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.A character array that delimits the substrings in this string, an empty array that contains no delimiters, or null.

options
StringSplitOptions StringSplitOptions StringSplitOptions StringSplitOptions

RemoveEmptyEntries para omitir los elementos de matriz vacíos de la matriz devuelta; o bien, None para incluir los elementos de matriz vacíos en la matriz devuelta.RemoveEmptyEntries to omit empty array elements from the array returned; or None to include empty array elements in the array returned.

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.

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 el StringSplitOptions enumeración para incluir o excluir las 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() methods that use
// the StringSplitOptions enumeration.
using System;

class Sample 
{
    public static void Main() 
    {
    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 \"{0}\".", s1);
    Console.WriteLine("The delimiter character is '{0}'.\n", 
                       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:\n");

// Display the original string and delimiter string.
    Console.WriteLine("2a) The original string is \"{0}\".", s2);
    Console.WriteLine("The delimiter string is \"{0}\".\n", 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);
    }

// Display the array of separated strings.
    public static void Show(string[] entries)
    {
    Console.WriteLine("The return value contains these {0} elements:", entries.Length);
    foreach (string entry in entries)
        {
        Console.Write("<{0}>", entry);
        }
    Console.Write("\n\n");
    }
}
/*
This example produces the following results:

1) Split a string delimited by characters:

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

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

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

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

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

2) Split a string delimited by another string:

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

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

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

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

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

*/

' This example demonstrates the String() methods that use
' the StringSplitOptions enumeration.
Imports System

Class Sample
    Public Shared Sub Main() 
        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 'Main
    
    
    ' 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 'Show
End Class 'Sample
'
'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

Detalles de valor devueltoReturn value details

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 en separator, la matriz devuelta consta de un solo 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 solo carácter.Each element of separator defines a separate delimiter that consists of a single character. Si el options argumento es Noney dos delimitadores son adyacentes o se encuentra un delimitador al principio o al final de esta instancia, el elemento correspondiente de la matriz 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 de la options argumento es None, el método devuelve una matriz de cadenas los siguientes cinco elementos: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 "-" 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 la "-" 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 a la "-" 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, caracteres de espacio en blanco se supone que los delimitadores.If the separator parameter is null or contains no characters, white-space characters are assumed to be the delimiters. Caracteres de espacio en blanco se definen mediante Unicode estándar y devuelven true si se pasan a la Char.IsWhiteSpace método.White-space characters are defined by the Unicode standard and return true if they are passed to the Char.IsWhiteSpace method.

Si el separator parámetro en la llamada a esta sobrecarga del método es null, se produce un error en la resolución de sobrecarga del compilador.If the separator parameter in the call to this method overload is null, compiler overload resolution fails. Para identificar de forma inequívoca el método llamado, el código debe indicar el tipo de la null.To unambiguously identify the called method, your code must indicate the type of the null. El ejemplo siguiente muestra varias maneras para identificar inequívocamente esta sobrecarga.The following example shows several ways to unambiguously identify this overload.

string phrase = "The quick  brown fox";
string[] words;

words = phrase.Split(default(Char[]), StringSplitOptions.RemoveEmptyEntries);

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

words = 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 la comparaciónComparison details

El Split método extrae las subcadenas de esta cadena que están delimitadas por uno o varios de los caracteres de la 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 realizar comparaciones usando las reglas de ordenación ordinal 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 acerca de la ordenación de palabras, cadena y ordinal, vea el 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

El Split métodos asignan memoria para el objeto de matriz devuelto y un String objeto para cada elemento de 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 administrar la asignación de memoria es fundamental en la aplicación, considere el uso de la IndexOf o IndexOfAny método y opcionalmente el Compare método para localizar una subcadena dentro de 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 va a dividir una cadena en un carácter separador, utilice el IndexOf o IndexOfAny método 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 va a dividir una cadena en una cadena separadora, utilice el IndexOf o IndexOfAny método 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, utilice el Compare método para determinar si los caracteres después de ese primer carácter son iguales a 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 el mismo conjunto de caracteres se utiliza para dividir las cadenas en varios 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 considerablemente 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 el .NET Framework 3,5.NET Framework 3.5 y versiones anteriores, si la Split(Char[]) se pasa al método un separator decir null o no contiene ningún carácter, el método usa un conjunto de caracteres ligeramente diferentes para dividir la cadena que el Trim(Char[]) hace el método para recorta la cadena.In the .NET Framework 3,5.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 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 de Unicode.Starting with the .NET Framework 4, both methods use an identical set of Unicode white-space characters.

Split(Char[], Int32) Split(Char[], Int32) Split(Char[], Int32) Split(Char[], Int32)

Divide una cadena en un número máximo de subcadenas en función de los caracteres de una matriz.Splits a string into a maximum number of substrings based on the characters in an array. Número máximo de subcadenas que se va devolver.You also specify the maximum number of substrings to return.

public:
 cli::array <System::String ^> ^ Split(cli::array <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.A character array that delimits the substrings in this string, an empty array that contains no delimiters, or null.

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

Ejemplos

En el ejemplo siguiente se muestra cómo count afecta al número de cadenas devuelta por Split.The following example demonstrates how count affects the number of strings returned by Split.

using System;

public class Example
{
   public static void Main() 
   {
      string delimStr = " ,.:";
      char [] delimiter = delimStr.ToCharArray();
      string words = "one two,three:four.";
      string [] split = null;

      Console.WriteLine("The delimiters are -{0}-", delimStr);
      for (int x = 1; x <= 5; x++) {
         split = words.Split(delimiter, x);
         Console.WriteLine("\ncount = {0,2} ..............", x);
         foreach (var s in split) {
             Console.WriteLine("-{0}-", s);
         }
      }
   }
}
// The example displays the following output:
//       The delimiters are - ,.:-
//       count =  1 ..............
//       -one two,three:four.-
//       count =  2 ..............
//       -one-
//       -two,three:four.-
//       count =  3 ..............
//       -one-
//       -two-
//       -three:four.-
//       count =  4 ..............
//       -one-
//       -two-
//       -three-
//       -four.-
//       count =  5 ..............
//       -one-
//       -two-
//       -three-
//       -four-
//       --
Public Class StringSplit2
   Public Shared Sub Main()
      
      Dim delimStr As String = " ,.:"
      Dim delimiter As Char() = delimStr.ToCharArray()
      Dim words As String = "one two,three:four."
      Dim split As String() = Nothing
      
      Console.WriteLine("The delimiters are -{0}-", delimStr)
      Dim x As Integer
      For x = 1 To 5
         split = words.Split(delimiter, x)
         Console.WriteLine(ControlChars.Cr + "count = {0,2} ..............", x)
         Dim s As String
         For Each s In  split
            Console.WriteLine("-{0}-", s)
         Next s
      Next x
   End Sub 
End Class 
' The example displays the following output:
'       The delimiters are - ,.:-
'       count =  1 ..............
'       -one two,three:four.-
'       count =  2 ..............
'       -one-
'       -two,three:four.-
'       count =  3 ..............
'       -one-
'       -two-
'       -three:four.-
'       count =  4 ..............
'       -one-
'       -two-
'       -three-
'       -four.-
'       count =  5 ..............
'       -one-
'       -two-
'       -three-
'       -four-
'       --

Comentarios

No se incluyen los caracteres delimitadores 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 en separator, la matriz devuelta consta de un solo 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, caracteres de espacio en blanco se supone que los delimitadores.If the separator parameter is null or contains no characters, white-space characters are assumed to be the delimiters. Caracteres de espacio en blanco se definen mediante Unicode estándar y devuelven true si se pasan a la Char.IsWhiteSpace método.White-space characters are defined by the Unicode standard and return true if they are passed to the Char.IsWhiteSpace method.

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 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 de esta instancia, la primera count menos 1 subcadenas se devuelven en la primera count menos 1 elementos del valor devuelto y los caracteres restantes de esta instancia se devuelven en los últimos 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 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 proporciona ejemplos.The following table provides examples.

Valor de cadenaString value SeparadorSeparator RecuentoCount Matriz devueltaReturned array
"42, 12, 19""42, 12, 19" nuevo Char [] {',', ' '} (C#)new Char[] {',', ' '} (C#)

Char() = {"," c, "" c} (Visual Basic)Char() = {","c, " "c} (Visual Basic)
22 {"42", " 12, 19"}{"42", " 12, 19"}
"42..12..19""42..12..19" new Char[] {'.'}new Char[] {'.'} (C#)(C#)

Char() = {"." c} (Visual Basic)Char() = {"."c} (Visual Basic)
44 {"42", "", "12", ".19"}{"42", "", "12", ".19"}
"Banana""Banana" new Char[] {'.'}new Char[] {'.'} (C#)(C#)

Char() = {"." c} (Visual Basic)Char() = {"."c} (Visual Basic)
22 {"Banana"}{"Banana"}
"Darb\nSmarba" (C#)"Darb\nSmarba" (C#)

VbLf "Darb" y "Smarba" (Visual Basic)"Darb" & vbLf & "Smarba" (Visual Basic)
nuevo Char [] {} (C#)new Char[] {} (C#)

Char() = {} (Visual Basic)Char() = {} (Visual Basic)
11 {"Darb\nSmarba"} (C#){"Darb\nSmarba"} (C#)

VbLf "Darb" y "Smarba" (Visual Basic)"Darb" & vbLf & "Smarba" (Visual Basic)
"Darb\nSmarba" (C#)"Darb\nSmarba" (C#)

VbLf "Darb" y "Smarba" (Visual Basic)"Darb" & vbLf & "Smarba" (Visual Basic)
nuevo Char [] null (C#)new Char[] null (C#)

Char() = NothingChar() = Nothing
22 {"Darb", "Smarba"}{"Darb", "Smarba"}
"Darb\nSmarba" (C#)"Darb\nSmarba" (C#)

VbLf "Darb" y "Smarba" (Visual Basic)"Darb" & vbLf & "Smarba" (Visual Basic)
nuevo Char [] null (C#)new Char[] null (C#)

Char() = NothingChar() = Nothing
100100 {"Darb", "Smarba"}{"Darb", "Smarba"}

Consideraciones sobre el rendimientoPerformance Considerations

El Split métodos asignan memoria para el objeto de matriz devuelto y un String objeto para cada elemento de 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 administrar la asignación de memoria es fundamental en la aplicación, considere el uso de la IndexOf o IndexOfAny método y opcionalmente el Compare método para localizar una subcadena dentro de 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 va a dividir una cadena en un carácter separador, utilice el IndexOf o IndexOfAny método 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 va a dividir una cadena en una cadena separadora, utilice el IndexOf o IndexOfAny método 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, utilice el Compare método para determinar si los caracteres después de ese primer carácter son iguales a 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 el mismo conjunto de caracteres se utiliza para dividir las cadenas en varios 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 considerablemente 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 el .NET Framework 3,5.NET Framework 3.5 y versiones anteriores, si la Split(Char[]) se pasa al método un separator decir null o no contiene ningún carácter, el método usa un conjunto de caracteres ligeramente diferentes para dividir la cadena que el Trim(Char[]) hace el método para recorta la cadena.In the .NET Framework 3,5.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 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 de Unicode.Starting with the .NET Framework 4, both methods use an identical set of Unicode white-space characters.

Consulte también:

Split(Char[]) Split(Char[]) Split(Char[]) Split(Char[])

Divide una cadena en subcadenas basadas en los caracteres de una matriz.Splits a string into substrings that are based on the characters in an array.

public:
 cli::array <System::String ^> ^ Split(... cli::array <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 que delimitan las subcadenas de esta cadena, una matriz vacía sin delimitadores o null.A character array that delimits the substrings in this string, 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

El ejemplo siguiente muestra cómo extraer palabras individuales de un bloque de texto tratando los espacios en blanco y signos de puntuación como delimitadores.The following example demonstrates how to extract individual words from a block of text by treating white space and punctuation marks as delimiters. La matriz de caracteres que se pasa a la separator parámetro de la String.Split(Char[]) método consta de un carácter de espacio y un carácter de tabulación, junto con algunos símbolos de puntuación comunes.The character array passed to the separator parameter of the String.Split(Char[]) method consists of a space character and a tab character, together with some common punctuation symbols.

using System;

public class SplitTest {
    public static void Main() {

        string words = "This is a list of words, with: a bit of punctuation" +
                       "\tand a tab character.";

        string [] split = words.Split(new Char [] {' ', ',', '.', ':', '\t' });

        foreach (string s in split) {

            if (s.Trim() != "")
                Console.WriteLine(s);
        }
    }
}
// The example displays the following output to the console:
//       This
//       is
//       a
//       list
//       of
//       words
//       with
//       a
//       bit
//       of
//       punctuation
//       and
//       a
//       tab
//       character
Public Class SplitTest
    Public Shared Sub Main()
        Dim words As String = "This is a list of words, with: a bit of punctuation" + _
                              vbTab + "and a tab character."
        Dim split As String() = words.Split(New [Char]() {" "c, ","c, "."c, ":"c, CChar(vbTab) })
                
        For Each s As String In  split
            If s.Trim() <> "" Then
                Console.WriteLine(s)
            End If
        Next s
    End Sub 'Main
End Class 'SplitTest
' The example displays the following output to the console:
'       This
'       is
'       a
'       list
'       of
'       words
'       with
'       a
'       bit
'       of
'       punctuation
'       and
'       a
'       tab
'       character

Comentarios

Cuando una cadena está delimitada por un conjunto conocido de caracteres, puede usar 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.

Detalles de valor devueltoReturn value details

No se incluyen los caracteres delimitadores 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 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 en separator, la matriz devuelta consta de un solo 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 en 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. A continuación se muestran algunos ejemplos:Here are some examples:

Valor de cadenaString value SeparadorSeparator Matriz devueltaReturned array
"42, 12, 19""42, 12, 19" nuevo Char [] {',', ' '} (C#)new Char[] {',', ' '} (C#)

Char() = {"," c, "" c}) (Visual Basic)Char() = {","c, " "c}) (Visual Basic)
{"42", "", "12", "", "19"}{"42", "", "12", "", "19"}
"42..12..19""42..12..19" new Char[] {'.'}new Char[] {'.'} (C#)(C#)

Char() = {"." c} (Visual Basic)Char() = {"."c} (Visual Basic)
{"42", "", "12", "", "19"}{"42", "", "12", "", "19"}
"Banana""Banana" new Char[] {'.'}new Char[] {'.'} (C#)(C#)

Char() = {"." c} (Visual Basic)Char() = {"."c} (Visual Basic)
{"Banana"}{"Banana"}
"Darb\nSmarba" (C#)"Darb\nSmarba" (C#)

VbLf "Darb" y "Smarba" (Visual Basic)"Darb" & vbLf & "Smarba" (Visual Basic)
nuevo Char [] {} (C#)new Char[] {} (C#)

Char() = {} (Visual Basic)Char() = {} (Visual Basic)
{"Darb", "Smarba"}{"Darb", "Smarba"}
"Darb\nSmarba" (C#)"Darb\nSmarba" (C#)

VbLf "Darb" y "Smarba" (Visual Basic)"Darb" & vbLf & "Smarba" (Visual Basic)
null (C#)null (C#)

Nothing (Visual Basic)Nothing (Visual Basic)
{"Darb", "Smarba"}{"Darb", "Smarba"}

La matriz de separadorThe separator array

Cada elemento de separador que define un delimitador independiente que consta de un solo 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 ningún carácter, 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. Caracteres de espacio en blanco se definen mediante el estándar; Unicode devuelven true si se pasan a la Char.IsWhiteSpace método.White-space characters are defined by the Unicode standard; they return true if they are passed to the Char.IsWhiteSpace method.

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

Aunque el parámetro único para esta sobrecarga de String.Split es una matriz de caracteres, podemos llamarlo con un carácter único, 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.

using System;

public class Example
{
   public static void Main()
   {
      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.
Module Example
   Public Sub Main()
      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
End Module
' The example displays the following output:
'     Thi
'      i
'      a
'     hort
'     tring.

Dado que el separator parámetro esté decorado con el ParamArrayAttribute atributo, compiladores interpretará un único carácter como una matriz de caracteres único elemento.Because the separator parameter is decorated with the ParamArrayAttribute attribute, compilers will interpret a single character as a single-element character array. Esto no es así para otros String.Split sobrecargas que incluyen un separator parámetro; debe pasar explícitamente estas sobrecargas de una matriz de caracteres como el 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 la 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 de 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 realizar comparaciones usando las reglas de ordenación ordinal 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 acerca de la ordenación de palabras, cadena y ordinal, vea el 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

El Split métodos asignan memoria para el objeto de matriz devuelto y un String objeto para cada elemento de 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 administrar la asignación de memoria es fundamental en la aplicación, considere el uso de la IndexOf o IndexOfAny método.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 localizar 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 el IndexOf o IndexOfAny método 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, utilice el IndexOf o IndexOfAny método 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, utilice el Compare método para determinar si los caracteres después de ese primer carácter son iguales a 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 el mismo conjunto de caracteres se utiliza para dividir las cadenas en varios 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 considerablemente 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 el .NET Framework 3,5.NET Framework 3.5 y versiones anteriores, si la Split(Char[]) se pasa al método un separator decir null o no contiene ningún carácter, el método usa un conjunto de caracteres ligeramente diferentes para dividir la cadena que el Trim(Char[]) hace el método para recorta la cadena.In the .NET Framework 3,5.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 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 de Unicode.Starting with the .NET Framework 4, both methods use an identical set of Unicode white-space characters.

Consulte también:

Split(String, StringSplitOptions) Split(String, StringSplitOptions) Split(String, StringSplitOptions)

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

Devoluciones

String[]

Se aplica a