String.Split Metodo

Definizione

Restituisce una matrice di stringhe contenente le sottostringhe di questa istanza delimitate dagli elementi di una stringa o matrice di caratteri Unicode specificata.

Overload

Split(Char[])

Divide una stringa in sottostringhe in base ai caratteri di delimitazione specificati.

Split(Char, StringSplitOptions)

Divide una stringa in sottostringhe in base al carattere di delimitazione specificato e, facoltativamente, ad altre opzioni.

Split(Char[], Int32)

Divide una stringa in un numero massimo di sottostringhe in base ai caratteri di delimitazione specificati.

Split(Char[], StringSplitOptions)

Divide una stringa in sottostringhe in base ai caratteri di delimitazione specificati e ad altre opzioni.

Split(String, StringSplitOptions)

Suddivide una stringa in sottostringhe in base al separatore di stringa specificato.

Split(String[], StringSplitOptions)

Divide una stringa in sottostringhe in base a una stringa di delimitazione specificata e, facoltativamente, ad altre opzioni.

Split(Char, Int32, StringSplitOptions)

Divide una stringa in un numero massimo di sottostringhe in base al carattere di delimitazione specificato e, facoltativamente, ad altre opzioni. Divide una stringa in un numero massimo di sottostringhe in base al separatore di caratteri specificato, omettendo facoltativamente le sottostringhe vuote dal risultato.

Split(Char[], Int32, StringSplitOptions)

Divide una stringa in un numero massimo di sottostringhe in base ai caratteri di delimitazione specificati e, facoltativamente, ad altre opzioni.

Split(String, Int32, StringSplitOptions)

Divide una stringa in un numero massimo di sottostringhe in base a una stringa di delimitazione specificata e, facoltativamente, ad altre opzioni.

Split(String[], Int32, StringSplitOptions)

Divide una stringa in un numero massimo di sottostringhe in base alle stringhe di delimitazione specificate e, facoltativamente, ad altre opzioni.

Commenti

Split viene usato per suddividere una stringa delimitata in sottostringhe. È possibile usare una matrice di caratteri o una matrice di stringhe per specificare zero o più caratteri o stringhe delimitatori. Se non vengono specificati caratteri di delimitazione, la stringa viene divisa in corrispondenza di spazi vuoti.

Gli overload del Split metodo consentono di limitare il numero di sottostringhe restituite dal metodo (il Split(Char[], Int32) metodo ), per specificare se includere stringhe vuote e/o tagliare le sottostringhe nel risultato (i Split(Char[], StringSplitOptions) metodi e Split(String[], StringSplitOptions) ) o eseguire entrambe le operazioni (i Split(Char[], Int32, StringSplitOptions) metodi e Split(String[], Int32, StringSplitOptions) ).

Suggerimento

Il Split metodo non è sempre il modo migliore per suddividere una stringa delimitata in sottostringhe. Se non si desidera estrarre tutte le sottostringhe di una stringa delimitata o se si vuole analizzare una stringa in base a un criterio anziché un set di caratteri delimitatori, è consigliabile usare espressioni regolari o combinare uno dei metodi di ricerca che restituisce l'indice di un carattere con il Substring metodo . Per altre informazioni, vedere Estrarre sottostringhe da una stringa.

Esempio

Negli esempi seguenti vengono illustrati tre overload diversi di String.Split(). Il primo esempio chiama l'overload Split(Char[]) e passa un singolo delimitatore.

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

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

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

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

let subs = s.Split ' '

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

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

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

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

Come si può notare, i caratteri punto (.) sono inclusi in due delle sottostringhe. Se si desidera escludere i caratteri punto, è possibile aggiungere il carattere punto come carattere di delimitazione aggiuntivo. Nell'esempio seguente viene illustrato come eseguire questa operazione.

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

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

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

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

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

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

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

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

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

I periodi sono passati dalle sottostringhe, ma ora sono state incluse due sottostringhe vuote aggiuntive. Queste sottostringa vuote rappresentano la sottostringa tra una parola e il punto che lo segue. Per omettere sottostringhe vuote dalla matrice risultante, è possibile chiamare l'overload Split(Char[], StringSplitOptions) e specificare StringSplitOptions.RemoveEmptyEntries per il options parametro .

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

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

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

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

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

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

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

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

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

Le sezioni per i singoli overload di String.Split() contengono altri esempi.

Split(Char[])

Divide una stringa in sottostringhe in base ai caratteri di delimitazione specificati.

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

Parametri

separator
Char[]

Matrice di caratteri di delimitazione, matrice vuota che non contiene delimitatori o null.

Restituisce

String[]

Matrice i cui elementi contengono le sottostringhe da questa istanza delimitate da uno o più caratteri in separator. Per altre informazioni, vedere la sezione Osservazioni.

Esempio

Nell'esempio seguente viene illustrato come estrarre singole parole da un blocco di testo trattando il carattere di spazio () e il carattere di tabulazione ( \t) come delimitatori. La stringa suddivisa include entrambi questi caratteri.

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

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

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

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

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

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

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

Commenti

Quando una stringa è delimitata da un set noto di caratteri, è possibile usare il Split(Char[]) metodo per separarlo in sottostringa.

I caratteri delimitatori non sono inclusi negli elementi della matrice restituita. Ad esempio, se la matrice separatore include il carattere "-" e il valore dell'istanza di stringa corrente è "aa-bb-cc", il metodo restituisce una matrice che contiene tre elementi: "aa", "bb" e "cc".

Se questa istanza non contiene alcun carattere in separator, la matrice restituita è costituita da un singolo elemento che contiene questa istanza.

Ogni elemento di separator definisce un carattere delimitatore separato. Se due delimitatori sono adiacenti o un delimitatore viene trovato all'inizio o alla fine di questa istanza, l'elemento corrispondente nella matrice restituita contiene Empty.

La tabella seguente illustra alcuni esempi.

Linguaggio Valore stringa Separatore Matrice restituita
C# "42, 12, 19" new Char[] {',', ' '} {"42", "", "12", "", "19"}
Visual Basic "42, 12, 19" Char() = {","c, " "c}) {"42", "", "12", "", "19"}
C# "42..12..19." new Char[] {'.'} {"42", "", "12", "", "19", ""}
Visual Basic "42..12..19." Char() = {"." c} {"42", "", "12", "", "19", ""}
C# "Banana" new Char[] {'.'} {"Banana"}
Visual Basic "Banana" Char() = {"." c} {"Banana"}
C# "Darb\nSmarba" new Char[] {} {"Darb", "Smarba"}
Visual Basic "Darb" & vbLf & "Smarba" Char() = {} {"Darb", "Smarba"}
C# "Darb\nSmarba" Null {"Darb", "Smarba"}
Visual Basic "Darb" & vbLf & "Smarba" Nothing {"Darb", "Smarba"}

Matrice separatore

Ogni elemento del separatore definisce un delimitatore separato costituito da un singolo carattere.

Se l'argomento è null o non contiene caratteri, il separator metodo considera gli spazi vuoti come delimitatori. I caratteri spazi vuoti sono definiti dallo standard Unicode e il Char.IsWhiteSpace metodo restituisce true se viene passato un carattere di spazio vuoto.

Stringa.Split(Char[]) e risoluzione dell'overload del compilatore

Anche se il singolo parametro per questo overload di è una matrice di String.Split caratteri, è possibile chiamarlo con un singolo carattere, come illustrato nell'esempio seguente.

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

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

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

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

Poiché il parametro viene decorato con l'attributo separatorParamArrayAttribute , i compilatori interpreteranno un singolo carattere come matrice di caratteri a singolo elemento. Questo non è il caso di altri String.Split overload che includono un separator parametro. È necessario passare in modo esplicito una matrice di caratteri come separator argomento.

Dettagli del confronto

Il Split(Char[]) metodo estrae le sottostringa in questa stringa delimitate da uno o più caratteri della separator matrice e restituisce tali sottostringa come elementi di una matrice.

Il Split(Char[]) metodo cerca delimitatori eseguendo confronti usando regole ordinali con distinzione tra maiuscole e minuscole. Per altre informazioni su word, string e ordinali, vedere l'enumerazione System.Globalization.CompareOptions .

Considerazioni sulle prestazioni

I Split metodi allocano memoria per l'oggetto matrice restituito e un String oggetto per ogni elemento della matrice. Se l'applicazione richiede prestazioni ottimali o se la gestione dell'allocazione della memoria è fondamentale nell'applicazione, prendere in considerazione l'uso del IndexOf metodo o IndexOfAny . È anche possibile usare il Compare metodo per individuare una sottostringa all'interno di una stringa.

Per dividere una stringa in un carattere separatore, usare il IndexOf metodo o IndexOfAny per individuare un carattere separatore nella stringa. Per dividere una stringa in una stringa separatore, usare il IndexOf metodo o IndexOfAny per individuare il primo carattere della stringa separatore. Usare quindi il Compare metodo per determinare se i caratteri dopo il primo carattere sono uguali ai caratteri rimanenti della stringa separatore.

Inoltre, se lo stesso set di caratteri viene usato per suddividere le stringhe in più Split chiamate di metodo, è consigliabile creare una singola matrice e fare riferimento a essa in ogni chiamata di metodo. Ciò riduce significativamente il sovraccarico aggiuntivo di ogni chiamata al metodo.

Note per i chiamanti

In .NET Framework 3.5 e versioni precedenti, se il metodo viene passato o separatornull non contiene caratteri, il Split(Char[]) metodo usa un set leggermente diverso di caratteri spazi vuoti per dividere la stringa rispetto Trim(Char[]) al metodo per tagliare la stringa. A partire da .NET Framework 4, entrambi i metodi usano un set identico di caratteri spazi vuoti Unicode.

Vedi anche

Si applica a

Split(Char, StringSplitOptions)

Divide una stringa in sottostringhe in base al carattere di delimitazione specificato e, facoltativamente, ad altre opzioni.

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

Parametri

separator
Char

Carattere che delimita le sottostringhe in questa stringa.

options
StringSplitOptions

Combinazione bit per bit dei valori di enumerazione, che specifica se tagliare le sottostringhe e includere le sottostringhe vuote.

Restituisce

String[]

Matrice i cui elementi contengono le sottostringhe da questa istanza delimitate da separator.

Si applica a

Split(Char[], Int32)

Divide una stringa in un numero massimo di sottostringhe in base ai caratteri di delimitazione specificati.

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

Parametri

separator
Char[]

Matrice di caratteri che delimitano le sottostringhe in questa stringa, matrice vuota senza delimitatori o null.

count
Int32

Numero massimo di sottostringhe da restituire.

Restituisce

String[]

Matrice i cui elementi contengono le sottostringhe in questa istanza delimitate da uno o più caratteri in separator. Per altre informazioni, vedere la sezione Osservazioni.

Eccezioni

count è negativo.

Esempio

Nell'esempio seguente viene illustrato come count è possibile usare per limitare il numero di stringhe restituite da Split.

string name = "Alex Johnson III";

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

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

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

let subs = name.Split(null, 2)

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

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

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

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

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

Commenti

I caratteri delimitatori non sono inclusi negli elementi della matrice restituita.

Se questa istanza non contiene alcun carattere in separator, la matrice restituita è costituita da un singolo elemento che contiene questa istanza. Se count è zero, viene restituita una matrice vuota.

Se il separator parametro è null o non contiene caratteri, si presuppone che i caratteri spazi vuoti siano i delimitatori. I caratteri spazi vuoti sono definiti dallo standard Unicode e il Char.IsWhiteSpace metodo restituisce true se vengono passati.

Ogni elemento di separator definisce un carattere delimitatore separato. Se due delimitatori sono adiacenti o un delimitatore viene trovato all'inizio o alla fine di questa istanza, l'elemento matrice corrispondente contiene Empty.

Se in questa istanza sono presenti più count sottostringa, le prime sottostringa vengono restituite nei primi count - 1count - 1 elementi del valore restituito e i caratteri rimanenti in questa istanza vengono restituiti nell'ultimo elemento del valore restituito.

Se count è maggiore del numero di sottostringa, le sottostringa disponibili vengono restituite e non viene generata alcuna eccezione.

La tabella seguente illustra alcuni esempi.

Linguaggio Valore stringa Separatore Matrice restituita
C# "42, 12, 19" new Char[] {',', ' '} {"42", "", "12", "", "19"}
Visual Basic "42, 12, 19" Char() = {","c, " "c}) {"42", "", "12", "", "19"}
C# "42..12..19." new Char[] {'.'} {"42", "", "12", "", "19", ""}
Visual Basic "42..12..19." Char() = {"." c} {"42", "", "12", "", "19", ""}
C# "Banana" new Char[] {'.'} {"Banana"}
Visual Basic "Banana" Char() = {"." c} {"Banana"}
C# "Darb\nSmarba" new Char[] {} {"Darb", "Smarba"}
Visual Basic "Darb" & vbLf & "Smarba" Char() = {} {"Darb", "Smarba"}
C# "Darb\nSmarba" Null {"Darb", "Smarba"}
Visual Basic "Darb" & vbLf & "Smarba" Nothing {"Darb", "Smarba"}

Considerazioni sulle prestazioni

I Split metodi allocano memoria per l'oggetto matrice restituito e un String oggetto per ogni elemento della matrice. Se l'applicazione richiede prestazioni ottimali o se la gestione dell'allocazione della memoria è fondamentale nell'applicazione, prendere in considerazione l'uso del IndexOfCompare metodo o IndexOfAny e, facoltativamente, per individuare una sottostringa all'interno di una stringa.

Se si divide una stringa in corrispondenza di un carattere separatore, usare il IndexOf metodo o IndexOfAny per individuare un carattere separatore nella stringa. Se si divide una stringa in una stringa separatore, usare il IndexOf metodo o IndexOfAny per individuare il primo carattere della stringa separatore. Usare quindi il Compare metodo per determinare se i caratteri dopo il primo carattere sono uguali ai caratteri rimanenti della stringa separatore.

Inoltre, se lo stesso set di caratteri viene usato per suddividere le stringhe in più Split chiamate di metodo, è consigliabile creare una singola matrice e fare riferimento a essa in ogni chiamata di metodo. Ciò riduce significativamente il sovraccarico aggiuntivo di ogni chiamata al metodo.

Note per i chiamanti

In .NET Framework 3.5 e versioni precedenti, se il metodo viene passato o separatornull non contiene caratteri, il Split(Char[]) metodo usa un set leggermente diverso di caratteri spazi vuoti per dividere la stringa rispetto Trim(Char[]) al metodo per tagliare la stringa. A partire da .NET Framework 4, entrambi i metodi usano un set identico di caratteri spazi vuoti Unicode.

Vedi anche

Si applica a

Split(Char[], StringSplitOptions)

Divide una stringa in sottostringhe in base ai caratteri di delimitazione specificati e ad altre opzioni.

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

Parametri

separator
Char[]

Matrice di caratteri che delimitano le sottostringhe in questa stringa, matrice vuota senza delimitatori o null.

options
StringSplitOptions

Combinazione bit per bit dei valori di enumerazione, che specifica se tagliare le sottostringhe e includere le sottostringhe vuote.

Restituisce

String[]

Matrice i cui elementi contengono le sottostringhe in questa stringa delimitate da uno o più caratteri in separator. Per altre informazioni, vedere la sezione Osservazioni.

Attributi

Eccezioni

options non è uno dei valori di StringSplitOptions.

Esempio

Nell'esempio seguente viene usata l'enumerazione StringSplitOptions per includere o escludere sottostringa generate dal Split metodo .

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

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

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

/*
This example produces the following results:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

/*
This example produces the following results:

1) Split a string delimited by characters:

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

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

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

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

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

2) Split a string delimited by another string:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

(*
This example produces the following results:

1) Split a string delimited by characters:

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

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

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

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

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

2) Split a string delimited by another string:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

End Sub


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

End Sub

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

Commenti

I caratteri delimitatori (i caratteri nella separator matrice) non sono inclusi negli elementi della matrice restituita. Ad esempio, se la separator matrice include il carattere "-" e il valore dell'istanza di stringa corrente è "aa-bb-cc", il metodo restituisce una matrice che contiene tre elementi: "aa", "bb" e "cc".

Se questa istanza non contiene alcun carattere in separator, la matrice restituita è costituita da un singolo elemento che contiene questa istanza.

Se il options parametro è e la lunghezza di questa istanza è RemoveEmptyEntries zero, il metodo restituisce una matrice vuota.

Ogni elemento di separator definisce un delimitatore separato costituito da un singolo carattere. Se l'argomento è None, e due delimitatori sono adiacenti o un delimitatore viene trovato all'inizio o alla fine di questa istanza, l'elemento options matrice corrispondente contiene String.Empty. Ad esempio, se separator include due elementi '-' e '_', il valore dell'istanza di stringa è "-_aa-_", e il valore dell'argomento options è None, il metodo restituisce una matrice di stringhe con i cinque elementi seguenti:

  1. String.Empty, che rappresenta la stringa vuota che precede il carattere "-" in corrispondenza dell'indice 0.

  2. String.Empty, che rappresenta la stringa vuota tra il carattere "-" in corrispondenza dell'indice 0 e il carattere "_" in corrispondenza dell'indice 1.

  3. "aa".

  4. String.Empty, che rappresenta la stringa vuota che segue il carattere "-" in corrispondenza dell'indice 4.

  5. String.Empty, che rappresenta la stringa vuota che segue il carattere "_" in corrispondenza dell'indice 5.

Matrice separatore

Se il separator parametro è null o non contiene caratteri, si presuppone che gli spazi vuoti siano i delimitatori. Gli spazi vuoti sono definiti dallo standard Unicode e il Char.IsWhiteSpace metodo restituisce true se vengono passati.

Per passare null per il char[] separator parametro , è necessario indicare il tipo di null per evitare ambiguità nella chiamata da altri overload, ad esempio Split(String[], StringSplitOptions). Nell'esempio seguente vengono illustrati diversi modi per identificare in modo non ambiguo questo overload.

string phrase = "The quick  brown fox";

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

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

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

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

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

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

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

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

Dettagli del confronto

Il Split metodo estrae le sottostringhe in questa stringa delimitate da uno o più caratteri nel separator parametro e restituisce tali sottostringhe come elementi di una matrice.

Il Split metodo cerca i delimitatori eseguendo confronti usando regole di ordinamento ordinale con distinzione tra maiuscole e minuscole. Per altre informazioni sugli ordinali di parole, stringhe e ordinali, vedere l'enumerazione System.Globalization.CompareOptions .

Considerazioni sulle prestazioni

I Split metodi allocano memoria per l'oggetto matrice restituito e un String oggetto per ogni elemento della matrice. Se l'applicazione richiede prestazioni ottimali o se la gestione dell'allocazione di memoria è fondamentale nell'applicazione, prendere in considerazione l'uso del IndexOf metodo o IndexOfAny e, facoltativamente, per Compare individuare una sottostringa all'interno di una stringa.

Se si divide una stringa in corrispondenza di un carattere separatore, usare il IndexOf metodo o IndexOfAny per individuare un carattere separatore nella stringa. Se si divide una stringa in una stringa separatore, usare il IndexOf metodo o IndexOfAny per individuare il primo carattere della stringa separatore. Utilizzare quindi il Compare metodo per determinare se i caratteri successivi al primo carattere sono uguali ai caratteri rimanenti della stringa separatore.

Inoltre, se lo stesso set di caratteri viene usato per suddividere le stringhe in più Split chiamate al metodo, è consigliabile creare una singola matrice e farvi riferimento in ogni chiamata al metodo. Ciò riduce significativamente il sovraccarico aggiuntivo di ogni chiamata al metodo.

Note per i chiamanti

In .NET Framework 3.5 e versioni precedenti, se il metodo viene passato o separatornull non contiene caratteri, il Split(Char[]) metodo usa un set leggermente diverso di caratteri spazi vuoti per dividere la stringa rispetto Trim(Char[]) al metodo per tagliare la stringa. A partire da .NET Framework 4, entrambi i metodi usano un set identico di caratteri spazi vuoti Unicode.

Si applica a

Split(String, StringSplitOptions)

Suddivide una stringa in sottostringhe in base al separatore di stringa specificato.

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

Parametri

separator
String

Stringa che delimita le sottostringhe in questa stringa.

options
StringSplitOptions

Combinazione bit per bit dei valori di enumerazione, che specifica se tagliare le sottostringhe e includere le sottostringhe vuote.

Restituisce

String[]

Matrice i cui elementi contengono le sottostringhe da questa istanza delimitate da separator.

Si applica a

Split(String[], StringSplitOptions)

Divide una stringa in sottostringhe in base a una stringa di delimitazione specificata e, facoltativamente, ad altre opzioni.

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

Parametri

separator
String[]

Matrice di stringhe che delimitano le sottostringhe in questa stringa, matrice vuota senza delimitatori o null.

options
StringSplitOptions

Combinazione bit per bit dei valori di enumerazione, che specifica se tagliare le sottostringhe e includere le sottostringhe vuote.

Restituisce

String[]

Matrice i cui elementi contengono le sottostringhe in questa stringa delimitate da una o più stringhe indicate in separator. Per altre informazioni, vedere la sezione Osservazioni.

Attributi

Eccezioni

options non è uno dei valori di StringSplitOptions.

Esempio

Nell'esempio seguente viene illustrata la differenza nelle matrici restituite chiamando il metodo di String.Split(String[], StringSplitOptions) una stringa con il relativo options parametro uguale a StringSplitOptions.None e StringSplitOptions.RemoveEmptyEntries.

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

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

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

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

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

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

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

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

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

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

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

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

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

Nell'esempio seguente viene definita una matrice di separatori che includono segni di punteggiatura e spazi vuoti. Passando questa matrice insieme a un valore di StringSplitOptions.RemoveEmptyEntries al Split(String[], StringSplitOptions) metodo restituisce una matrice costituita dalle singole parole della stringa.

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

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

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

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

Si noti che il metodo viene chiamato con l'argomento options impostato su StringSplitOptions.RemoveEmptyEntries. Ciò impedisce alla matrice restituita di includere String.Empty valori che rappresentano corrispondenze di sottostringa vuote tra segni di punteggiatura e spazi vuoti.

Commenti

Quando una stringa è delimitata da un set noto di stringhe, è possibile usare il Split metodo per separarlo in sottostringhe.

Le stringhe delimitatore non sono incluse negli elementi della matrice restituita. Ad esempio, se la separator matrice include la stringa "--" e il valore dell'istanza di stringa corrente è "aa--bb--cc", il metodo restituisce una matrice contenente tre elementi: "aa", "bb" e "cc".

Se questa istanza non contiene alcuna stringa in separator, la matrice restituita è costituita da un singolo elemento che contiene questa istanza.

Se il options parametro è RemoveEmptyEntries e la lunghezza di questa istanza è zero, il metodo restituisce una matrice vuota.

Ogni elemento di separator definisce un delimitatore separato costituito da uno o più caratteri. Se l'argomento options è Nonee due delimitatori sono adiacenti o un delimitatore viene trovato all'inizio o alla fine di questa istanza, l'elemento della matrice corrispondente contiene String.Empty. Ad esempio, se separator include due elementi, "-" e "_", il valore dell'istanza di stringa è "-_aa-_" e il valore dell'argomento options è None, il metodo restituisce una matrice di stringhe con i cinque elementi seguenti:

  1. String.Empty, che rappresenta la stringa vuota che precede la sottostringa "-" in corrispondenza dell'indice 0.

  2. String.Empty, che rappresenta la stringa vuota tra la sottostringa "-" in corrispondenza dell'indice 0 e la sottostringa "_" in corrispondenza dell'indice 1.

  3. "aa".

  4. String.Empty, che rappresenta la stringa vuota che segue la sottostringa "-" in corrispondenza dell'indice 4.

  5. String.Empty, che rappresenta la stringa vuota che segue la sottostringa "_" in corrispondenza dell'indice 5.

Matrice separatore

Se uno degli elementi in separator è costituito da più caratteri, l'intera sottostringa viene considerata un delimitatore. Ad esempio, se uno degli elementi in separator è "10", tentando di dividere la stringa "This10is10a10string". restituisce la matrice di quattro elementi seguente: { "This", "is", "a", "string". }.

Se il separator parametro è null o non contiene stringhe non vuote, si presuppone che gli spazi vuoti siano i delimitatori. Gli spazi vuoti sono definiti dallo standard Unicode e il Char.IsWhiteSpace metodo restituisce true se vengono passati.

Per passare null per il string[] separator parametro , è necessario indicare il tipo di null per evitare ambiguità nella chiamata da altri overload, ad esempio Split(Char[], StringSplitOptions). Nell'esempio seguente vengono illustrati diversi modi per identificare in modo non ambiguo questo overload.

string phrase = "The quick  brown fox";

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

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

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

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

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

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

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

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

Dettagli del confronto

Il Split metodo estrae le sottostringhe in questa stringa delimitate da una o più stringhe nel separator parametro e restituisce tali sottostringhe come elementi di una matrice.

Il Split metodo cerca i delimitatori eseguendo confronti usando regole di ordinamento ordinale con distinzione tra maiuscole e minuscole. Per altre informazioni sugli ordinali di parole, stringhe e ordinali, vedere l'enumerazione System.Globalization.CompareOptions .

Il Split metodo ignora qualsiasi elemento del separator cui valore è null o la stringa vuota ("").

Per evitare risultati ambigui quando le stringhe in separator hanno caratteri in comune, l'operazione Split procede dall'inizio alla fine del valore dell'istanza e corrisponde al primo elemento in separator che è uguale a un delimitatore nell'istanza. L'ordine in cui vengono rilevate sottostringhe nell'istanza ha la precedenza sull'ordine degli elementi in separator.

Si consideri ad esempio un'istanza il cui valore è "abcdef". Se il primo elemento in separator era "ef" e il secondo elemento era "bcde", il risultato dell'operazione di divisione sarebbe una matrice di stringhe che contiene due elementi, "a" e "f". Ciò è dovuto al fatto che viene rilevata la sottostringa nell'istanza "bcde" e corrisponde a un elemento in separator prima che venga rilevata la sottostringa "f".

Tuttavia, se il primo elemento di separator è "bcd" e il secondo elemento è "bc", il risultato dell'operazione di divisione sarà una matrice di stringhe che contiene due elementi, "a" e "ef". Ciò è dovuto al fatto che "bcd" è il primo delimitatore in separator che corrisponde a un delimitatore nell'istanza di . Se l'ordine dei separatori è stato invertito in modo che il primo elemento fosse "bc" e il secondo elemento fosse "bcd", il risultato sarebbe una matrice di stringhe che contiene due elementi, "a" e "def".

Considerazioni sulle prestazioni

I Split metodi allocano memoria per l'oggetto matrice restituito e un String oggetto per ogni elemento della matrice. Se l'applicazione richiede prestazioni ottimali o se la gestione dell'allocazione di memoria è fondamentale nell'applicazione, prendere in considerazione l'uso del IndexOf metodo o IndexOfAny e, facoltativamente, per Compare individuare una sottostringa all'interno di una stringa.

Se si divide una stringa in corrispondenza di un carattere separatore, usare il IndexOf metodo o IndexOfAny per individuare un carattere separatore nella stringa. Se si divide una stringa in una stringa separatore, usare il IndexOf metodo o IndexOfAny per individuare il primo carattere della stringa separatore. Utilizzare quindi il Compare metodo per determinare se i caratteri successivi al primo carattere sono uguali ai caratteri rimanenti della stringa separatore.

Inoltre, se lo stesso set di caratteri viene usato per suddividere le stringhe in più Split chiamate al metodo, è consigliabile creare una singola matrice e farvi riferimento in ogni chiamata al metodo. Ciò riduce significativamente il sovraccarico aggiuntivo di ogni chiamata al metodo.

Note per i chiamanti

In .NET Framework 3.5 e versioni precedenti, se il Split(Char[]) metodo viene passato o separatornull non contiene caratteri, il metodo usa un set leggermente diverso di caratteri spazi vuoti per dividere la stringa rispetto Trim(Char[]) al metodo per tagliare la stringa. A partire da .NET Framework 4, entrambi i metodi usano un set identico di caratteri di spazio vuoto Unicode.

Si applica a

Split(Char, Int32, StringSplitOptions)

Divide una stringa in un numero massimo di sottostringhe in base al carattere di delimitazione specificato e, facoltativamente, ad altre opzioni. Divide una stringa in un numero massimo di sottostringhe in base al separatore di caratteri specificato, omettendo facoltativamente le sottostringhe vuote dal risultato.

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

Parametri

separator
Char

Carattere che delimita le sottostringhe in questa istanza.

count
Int32

Numero massimo di elementi previsti nella matrice.

options
StringSplitOptions

Combinazione bit per bit dei valori di enumerazione, che specifica se tagliare le sottostringhe e includere le sottostringhe vuote.

Restituisce

String[]

Matrice che contiene al massimo count sottostringhe da questa istanza delimitate da separator.

Commenti

Se la stringa è già stata divisa count - 1 volte, ma la fine della stringa non è stata raggiunta, l'ultima stringa nella matrice restituita conterrà la sottostringa finale rimanente di questa istanza, non modificata.

Si applica a

Split(Char[], Int32, StringSplitOptions)

Divide una stringa in un numero massimo di sottostringhe in base ai caratteri di delimitazione specificati e, facoltativamente, ad altre opzioni.

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

Parametri

separator
Char[]

Matrice di caratteri che delimitano le sottostringhe in questa stringa, matrice vuota senza delimitatori o null.

count
Int32

Numero massimo di sottostringhe da restituire.

options
StringSplitOptions

Combinazione bit per bit dei valori di enumerazione, che specifica se tagliare le sottostringhe e includere le sottostringhe vuote.

Restituisce

String[]

Matrice che contiene le sottostringhe in questa stringa delimitate da uno o più caratteri in separator. Per altre informazioni, vedere la sezione Osservazioni.

Attributi

Eccezioni

count è negativo.

options non è uno dei valori di StringSplitOptions.

Esempio

Nell'esempio seguente viene utilizzata l'enumerazione StringSplitOptions per includere o escludere sottostringhe generate dal Split metodo .

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

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

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

/*
This example produces the following results:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

/*
This example produces the following results:

1) Split a string delimited by characters:

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

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

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

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

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

2) Split a string delimited by another string:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

(*
This example produces the following results:

1) Split a string delimited by characters:

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

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

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

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

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

2) Split a string delimited by another string:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

End Sub


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

End Sub

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

Commenti

I caratteri delimitatori non sono inclusi negli elementi della matrice restituita.

Se questa istanza non contiene alcun carattere in separatoro il count parametro è 1, la matrice restituita è costituita da un singolo elemento che contiene questa istanza.

Se il separator parametro è null o non contiene caratteri, si presuppone che gli spazi vuoti siano i delimitatori. Gli spazi vuoti sono definiti dallo standard Unicode e il Char.IsWhiteSpace metodo restituisce true se vengono passati.

Per passare null per il char[] separator parametro , è necessario indicare il tipo di null per evitare ambiguità nella chiamata da altri overload, ad esempio Split(String[], Int32, StringSplitOptions). Nell'esempio seguente vengono illustrati diversi modi per identificare in modo non ambiguo questo overload.

string phrase = "The quick  brown fox";

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

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

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

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

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

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

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

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

Se il count parametro è zero o il options parametro è RemoveEmptyEntries e la lunghezza di questa istanza è zero, viene restituita una matrice vuota.

Ogni elemento di separator definisce un carattere delimitatore separato. Se il options parametro è Nonee due delimitatori sono adiacenti o un delimitatore viene trovato all'inizio o alla fine di questa istanza, l'elemento della matrice corrispondente contiene Empty.

Se in questa istanza sono presenti più count sottostringhe, le prime count sottostringhe meno 1 vengono restituite nei primi count meno 1 elementi del valore restituito e i caratteri rimanenti in questa istanza vengono restituiti nell'ultimo elemento del valore restituito.

Se count è maggiore del numero di sottostringhe, vengono restituite le sottostringhe disponibili e non viene generata alcuna eccezione.

Considerazioni sulle prestazioni

I Split metodi allocano memoria per l'oggetto matrice restituito e un String oggetto per ogni elemento della matrice. Se l'applicazione richiede prestazioni ottimali o se la gestione dell'allocazione di memoria è fondamentale nell'applicazione, prendere in considerazione l'uso del IndexOf metodo o IndexOfAny e, facoltativamente, per Compare individuare una sottostringa all'interno di una stringa.

Se si divide una stringa in corrispondenza di un carattere separatore, usare il IndexOf metodo o IndexOfAny per individuare un carattere separatore nella stringa. Se si divide una stringa in una stringa separatore, usare il IndexOf metodo o IndexOfAny per individuare il primo carattere della stringa separatore. Utilizzare quindi il Compare metodo per determinare se i caratteri successivi al primo carattere sono uguali ai caratteri rimanenti della stringa separatore.

Inoltre, se lo stesso set di caratteri viene usato per suddividere le stringhe in più Split chiamate al metodo, è consigliabile creare una singola matrice e farvi riferimento in ogni chiamata al metodo. Ciò riduce significativamente il sovraccarico aggiuntivo di ogni chiamata al metodo.

Note per i chiamanti

In .NET Framework 3.5 e versioni precedenti, se il Split(Char[]) metodo viene passato o separatornull non contiene caratteri, il metodo usa un set leggermente diverso di caratteri spazi vuoti per dividere la stringa rispetto Trim(Char[]) al metodo per tagliare la stringa. A partire da .NET Framework 4, entrambi i metodi usano un set identico di caratteri di spazio vuoto Unicode.

Si applica a

Split(String, Int32, StringSplitOptions)

Divide una stringa in un numero massimo di sottostringhe in base a una stringa di delimitazione specificata e, facoltativamente, ad altre opzioni.

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

Parametri

separator
String

Stringa che delimita le sottostringhe in questa istanza.

count
Int32

Numero massimo di elementi previsti nella matrice.

options
StringSplitOptions

Combinazione bit per bit dei valori di enumerazione, che specifica se tagliare le sottostringhe e includere le sottostringhe vuote.

Restituisce

String[]

Matrice che contiene al massimo count sottostringhe da questa istanza delimitate da separator.

Commenti

Se la stringa è già stata divisa count - 1 volte, ma la fine della stringa non è stata raggiunta, l'ultima stringa nella matrice restituita conterrà la sottostringa finale rimanente di questa istanza, non modificata.

Si applica a

Split(String[], Int32, StringSplitOptions)

Divide una stringa in un numero massimo di sottostringhe in base alle stringhe di delimitazione specificate e, facoltativamente, ad altre opzioni.

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

Parametri

separator
String[]

Stringhe che delimitano le sottostringhe in questa stringa, matrice vuota senza delimitatori o null.

count
Int32

Numero massimo di sottostringhe da restituire.

options
StringSplitOptions

Combinazione bit per bit dei valori di enumerazione, che specifica se tagliare le sottostringhe e includere le sottostringhe vuote.

Restituisce

String[]

Matrice i cui elementi contengono le sottostringhe in questa stringa delimitate da una o più stringhe indicate in separator. Per altre informazioni, vedere la sezione Osservazioni.

Attributi

Eccezioni

count è negativo.

options non è uno dei valori di StringSplitOptions.

Esempio

Nell'esempio seguente viene utilizzata l'enumerazione StringSplitOptions per includere o escludere sottostringhe generate dal Split metodo .

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

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

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

/*
This example produces the following results:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

/*
This example produces the following results:

1) Split a string delimited by characters:

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

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

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

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

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

2) Split a string delimited by another string:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

(*
This example produces the following results:

1) Split a string delimited by characters:

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

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

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

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

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

2) Split a string delimited by another string:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

End Sub


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

End Sub

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

Commenti

Le stringhe delimitatore non sono incluse negli elementi della matrice restituita.

Se questa istanza non contiene alcuna stringa in separatoro il count parametro è 1, la matrice restituita è costituita da un singolo elemento che contiene questa istanza.

Se il separator parametro è null o non contiene caratteri, si presuppone che gli spazi vuoti siano i delimitatori. Gli spazi vuoti sono definiti dallo standard Unicode e il Char.IsWhiteSpace metodo restituisce true se vengono passati.

Per passare null per il string[] separator parametro , è necessario indicare il tipo di null per evitare ambiguità nella chiamata da altri overload, ad esempio Split(Char[], Int32, StringSplitOptions). Nell'esempio seguente vengono illustrati diversi modi per identificare in modo non ambiguo questo overload.

string phrase = "The quick  brown fox";

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

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

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

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

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

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

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

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

Se il count parametro è zero o il options parametro è RemoveEmptyEntries e la lunghezza di questa istanza è zero, viene restituita una matrice vuota.

Ogni elemento di separator definisce un delimitatore separato costituito da uno o più caratteri. Se il options parametro è Nonee due delimitatori sono adiacenti o un delimitatore viene trovato all'inizio o alla fine di questa istanza, l'elemento della matrice corrispondente contiene Empty.

Se in questa istanza sono presenti più count sottostringhe, le prime count sottostringhe meno 1 vengono restituite nei primi count meno 1 elementi del valore restituito e i caratteri rimanenti in questa istanza vengono restituiti nell'ultimo elemento del valore restituito.

Se count è maggiore del numero di sottostringhe, vengono restituite le sottostringhe disponibili e non viene generata alcuna eccezione.

Matrice separatore

Se uno degli elementi in separator è costituito da più caratteri, l'intera sottostringa viene considerata un delimitatore. Ad esempio, se uno degli elementi in separator è "10", il tentativo di dividere la stringa "This10is10a10string". restituisce questa matrice di quattro elementi: { "This", "is", "a", "string". }.

Dettagli del confronto

Il Split metodo estrae le sottostringhe in questa stringa delimitate da una o più stringhe nel separator parametro e restituisce tali sottostringhe come elementi di una matrice.

Il Split metodo cerca i delimitatori eseguendo confronti usando regole di ordinamento ordinale con distinzione tra maiuscole e minuscole. Per altre informazioni sugli ordinali di parole, stringhe e ordinali, vedere l'enumerazione System.Globalization.CompareOptions .

Il Split metodo ignora qualsiasi elemento del separator cui valore è null o la stringa vuota ("").

Per evitare risultati ambigui quando le stringhe in separator hanno caratteri in comune, il Split metodo procede dall'inizio alla fine del valore dell'istanza e corrisponde al primo elemento in separator che è uguale a un delimitatore nell'istanza di . L'ordine in cui vengono rilevate sottostringhe nell'istanza ha la precedenza sull'ordine degli elementi in separator.

Si consideri ad esempio un'istanza il cui valore è "abcdef". Se il primo elemento in separator era "ef" e il secondo elemento era "bcde", il risultato dell'operazione di divisione sarebbe "a" e "f". Ciò è dovuto al fatto che viene rilevata la sottostringa nell'istanza "bcde" e corrisponde a un elemento in separator prima che venga rilevata la sottostringa "f".

Tuttavia, se il primo elemento di separator era "bcd" e il secondo elemento era "bc", il risultato dell'operazione di divisione sarebbe "a" ed "ef". Ciò è dovuto al fatto che "bcd" è il primo delimitatore in separator che corrisponde a un delimitatore nell'istanza di . Se l'ordine dei separatori è stato invertito in modo che il primo elemento sia "bc" e il secondo elemento sia "bcd", il risultato sarà "a" e "def".

Considerazioni sulle prestazioni

I Split metodi allocano memoria per l'oggetto matrice restituito e un String oggetto per ogni elemento della matrice. Se l'applicazione richiede prestazioni ottimali o se la gestione dell'allocazione di memoria è fondamentale nell'applicazione, prendere in considerazione l'uso del IndexOf metodo o IndexOfAny e, facoltativamente, per Compare individuare una sottostringa all'interno di una stringa.

Se si divide una stringa in corrispondenza di un carattere separatore, usare il IndexOf metodo o IndexOfAny per individuare un carattere separatore nella stringa. Se si divide una stringa in una stringa separatore, usare il IndexOf metodo o IndexOfAny per individuare il primo carattere della stringa separatore. Utilizzare quindi il Compare metodo per determinare se i caratteri successivi al primo carattere sono uguali ai caratteri rimanenti della stringa separatore.

Inoltre, se lo stesso set di caratteri viene usato per suddividere le stringhe in più Split chiamate al metodo, è consigliabile creare una singola matrice e farvi riferimento in ogni chiamata al metodo. Ciò riduce significativamente il sovraccarico aggiuntivo di ogni chiamata al metodo.

Note per i chiamanti

In .NET Framework 3.5 e versioni precedenti, se il Split(Char[]) metodo viene passato o separatornull non contiene caratteri, il metodo usa un set leggermente diverso di caratteri spazi vuoti per dividere la stringa rispetto Trim(Char[]) al metodo per tagliare la stringa. A partire da .NET Framework 4, entrambi i metodi usano un set identico di caratteri di spazio vuoto Unicode.

Si applica a