String.Split Metoda

Definicja

Zwraca tablicę ciągów zawierającą podciągi w tym wystąpieniu, które są rozdzielane elementami określonego ciągu lub tablicy znaków Unicode.

Przeciążenia

Split(Char[])

Dzieli ciąg na podciągi na podstawie określonych znaków ograniczników.

Split(Char, StringSplitOptions)

Dzieli ciąg na podciągi na podstawie określonego znaku ogranicznika i, opcjonalnie, opcji.

Split(Char[], Int32)

Dzieli ciąg na maksymalną liczbę podciągów na podstawie określonych znaków ograniczników.

Split(Char[], StringSplitOptions)

Dzieli ciąg na podciągi na podstawie określonych znaków i opcji ograniczników.

Split(String, StringSplitOptions)

Dzieli ciąg na podciągy oparte na podanym separatorze ciągów.

Split(String[], StringSplitOptions)

Dzieli ciąg na podciągi na podstawie określonego ciągu rozdzielającego i, opcjonalnie, opcji.

Split(Char, Int32, StringSplitOptions)

Dzieli ciąg na maksymalną liczbę podciągów na podstawie określonego znaku ogranicznika i opcjonalnie opcji. Dzieli ciąg na maksymalną liczbę podciągów na podstawie podanego separatora znaków, opcjonalnie pomijając puste podciągy z wyniku.

Split(Char[], Int32, StringSplitOptions)

Dzieli ciąg na maksymalną liczbę podciągów na podstawie określonych znaków ograniczników i, opcjonalnie, opcji.

Split(String, Int32, StringSplitOptions)

Dzieli ciąg na maksymalną liczbę podciągów na podstawie określonego ciągu ogranicznika i opcjonalnie opcji.

Split(String[], Int32, StringSplitOptions)

Dzieli ciąg na maksymalną liczbę podciągów na podstawie określonych ciągów ograniczników i opcjonalnie opcji.

Uwagi

Split służy do dzielenia rozdzielanego ciągu na podciągi. Można użyć tablicy znaków lub tablicy ciągów, aby określić zero lub więcej znaków ograniczników lub ciągów. Jeśli nie określono żadnych znaków ograniczników, ciąg jest podzielony na znaki odstępu.

Przeciążenia Split metody pozwalają ograniczyć liczbę podciągów zwracanych przez metodę ( Split(Char[], Int32) metodę), aby określić, czy mają być uwzględniane puste ciągi i/lub przycinanie podciągów w wyniku ( Split(Char[], StringSplitOptions) metody i Split(String[], StringSplitOptions) ) lub do wykonania obu metod (metody Split(Char[], Int32, StringSplitOptions) i Split(String[], Int32, StringSplitOptions) ).

Porada

Metoda Split nie zawsze jest najlepszym sposobem podziału rozdzielanego ciągu na podciągi. Jeśli nie chcesz wyodrębniać wszystkich podciągów ciągu rozdzielanego lub jeśli chcesz przeanalizować ciąg na podstawie wzorca zamiast zestawu znaków ograniczników, rozważ użycie wyrażeń regularnych lub połączenie jednej z metod wyszukiwania, która zwraca indeks znaku z Substring metodą . Aby uzyskać więcej informacji, zobacz Wyodrębnianie podciągów z ciągu.

Przykład

W poniższych przykładach pokazano trzy różne przeciążenia elementu String.Split(). Pierwszy przykład wywołuje Split(Char[]) przeciążenie i przechodzi w jednym ograniczniku.

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.

Jak widać, znaki kropki (.) są uwzględniane w dwóch podciągach. Jeśli chcesz wykluczyć znaki kropki, możesz dodać znak kropki jako dodatkowy znak ogranicznika. W następnym przykładzie pokazano, jak to zrobić.

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:

Okresy zniknęły z podciągów, ale teraz zostały uwzględnione dwa dodatkowe puste podciągy. Te puste podciągy reprezentują podciąg między wyrazem a kropką, która następuje po nim. Aby pominąć puste podciągy z wynikowej tablicy, można wywołać Split(Char[], StringSplitOptions) przeciążenie i określić StringSplitOptions.RemoveEmptyEntries parametr options .

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

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

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

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

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

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

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

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

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

Sekcje poszczególnych przeciążeń zawierają String.Split() dalsze przykłady.

Split(Char[])

Dzieli ciąg na podciągi na podstawie określonych znaków ograniczników.

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

Parametry

separator
Char[]

Tablica znaków rozdzielających, pusta tablica, która nie zawiera ograniczników ani null.

Zwraca

String[]

Tablica, której elementy zawierają podciągi z tego wystąpienia, które są rozdzielone przez co najmniej jeden znak w .separator Aby uzyskać więcej informacji, zobacz sekcję: Uwagi.

Przykłady

W poniższym przykładzie pokazano, jak wyodrębnić poszczególne wyrazy z bloku tekstu, traktując znak spacji ( ) i znak tabulatora (\t) jako ograniczniki. Rozdzielany ciąg zawiera oba te znaki.

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

Uwagi

Gdy ciąg jest rozdzielany przez znany zestaw znaków, można użyć Split(Char[]) metody , aby oddzielić go od podciągów.

Znaki ogranicznika nie są uwzględnione w elementach zwróconej tablicy. Jeśli na przykład tablica separatora zawiera znak "-", a wartość bieżącego wystąpienia ciągu to "aa-bb-cc", metoda zwraca tablicę zawierającą trzy elementy: "aa", "bb" i "cc".

Jeśli to wystąpienie nie zawiera żadnych znaków w separatorobiekcie , zwracana tablica składa się z jednego elementu zawierającego to wystąpienie.

Każdy element definiuje separator oddzielny znak ogranicznika. Jeśli dwa ograniczniki są sąsiadujące lub ogranicznik znajduje się na początku lub na końcu tego wystąpienia, odpowiedni element w zwracanej tablicy zawiera Emptywartość .

W poniższej tabeli przedstawiono kilka przykładów.

Język Wartość ciągu Separator Zwracana tablica
C# "42, 12, 19" new Char[] {',', ' '} {"42", "", "12", "", "19"}
Visual Basic "42, 12, 19" Char() = {","c, " "c}) {"42", "", "12", "", "19"}
C# "42..12..19." nowy znak[] {'.'} {"42", "", "12", "", "19", ""}
Visual Basic "42..12..19." Char() = {"." c} {"42", "", "12", "", "19", ""}
C# "Banan" nowy znak[] {'.'} {"Banana"}
Visual Basic "Banan" Char() = {"." c} {"Banana"}
C# "Darb\nSmarba" nowy znak[] {} {"Darb", "Smarba"}
Visual Basic "Darb" & vbLf & "Smarba" Char() = {} {"Darb", "Smarba"}
C# "Darb\nSmarba" null {"Darb", "Smarba"}
Visual Basic "Darb" & vbLf & "Smarba" Nothing {"Darb", "Smarba"}

Tablica separatorów

Każdy element separatora definiuje oddzielny ogranicznik, który składa się z pojedynczego znaku.

separator Jeśli argument jest null lub nie zawiera znaków, metoda traktuje znaki odstępu jako ograniczniki. Znaki odstępu są definiowane przez standard Unicode, a Char.IsWhiteSpace metoda zwraca true wartość , jeśli do niej zostanie przekazany znak odstępu.

String.Split(Char[]) i rozpoznawanie przeciążenia kompilatora

Chociaż pojedynczy parametr dla tego przeciążenia String.Split jest tablicą znaków, można wywołać go z pojedynczym znakiem, jak pokazano w poniższym przykładzie.

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.

separator Ponieważ parametr jest ozdobiony atrybutemParamArrayAttribute, kompilatory zinterpretują pojedynczy znak jako tablicę znaków z jednym elementem. Nie jest tak w przypadku innych String.Split przeciążeń, które zawierają separator parametr; należy jawnie przekazać te przeciążenia tablicy znaków jako argument.separator

Szczegóły porównania

Metoda Split(Char[]) wyodrębnia podciągi w tym ciągu, które są rozdzielane przez co najmniej jeden znak w separator tablicy, i zwraca te podciągi jako elementy tablicy.

Metoda Split(Char[]) wyszukuje ograniczniki, wykonując porównania przy użyciu reguł sortowania porządkowego uwzględniających wielkość liter. Aby uzyskać więcej informacji na temat sortowania wyrazów, ciągów i porządkowych, zobacz System.Globalization.CompareOptions wyliczenie.

Zagadnienia dotyczące wydajności

Metody Split przydzielają pamięć dla zwróconego obiektu tablicy i String obiektu dla każdego elementu tablicy. Jeśli aplikacja wymaga optymalnej wydajności lub jeśli zarządzanie alokacją pamięci ma krytyczne znaczenie w aplikacji, rozważ użycie IndexOf metody lub IndexOfAny . Istnieje również możliwość użycia Compare metody w celu zlokalizowania podciągów w ciągu.

Aby podzielić ciąg na znak separatora, użyj IndexOf metody or IndexOfAny , aby zlokalizować znak separatora w ciągu. Aby podzielić ciąg w ciągu separatora, użyj IndexOf metody or IndexOfAny , aby zlokalizować pierwszy znak ciągu separatora. Następnie użyj Compare metody , aby określić, czy znaki po tym pierwszym znaku są równe pozostałym znakom ciągu separatora.

Ponadto, jeśli ten sam zestaw znaków jest używany do dzielenia ciągów w wielu Split wywołaniach metody, rozważ utworzenie pojedynczej tablicy i odwołanie do niej w każdym wywołaniu metody. Pozwala to znacznie ograniczyć dodatkowe obciążenie każdego wywołania metody.

Uwagi dotyczące wywoływania

W .NET Framework 3.5 i starszych wersjach, jeśli Split(Char[]) metoda jest przekazywana separatornull lub nie zawiera znaków, metoda używa nieco innego zestawu znaków odstępu, aby podzielić ciąg niż Trim(Char[]) metoda, aby przyciąć ciąg. Począwszy od .NET Framework 4, obie metody używają identycznego zestawu znaków odstępów Unicode.

Zobacz też

Dotyczy

Split(Char, StringSplitOptions)

Dzieli ciąg na podciągi na podstawie określonego znaku ogranicznika i, opcjonalnie, opcji.

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

Parametry

separator
Char

Znak, który rozdziela podciągi w tym ciągu.

options
StringSplitOptions

Bitowa kombinacja wartości wyliczenia, która określa, czy przycinać podciągy i uwzględniać puste podciągy.

Zwraca

String[]

Tablica, której elementy zawierają podciągi z tego wystąpienia, które są rozdzielane przez separator.

Dotyczy

Split(Char[], Int32)

Dzieli ciąg na maksymalną liczbę podciągów na podstawie określonych znaków ograniczników.

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

Parametry

separator
Char[]

Tablica znaków rozdzielających podciągi w tym ciągu, pustą tablicę, która nie zawiera ograniczników ani null.

count
Int32

Maksymalna liczba podciągów do zwrócenia.

Zwraca

String[]

Tablica, której elementy zawierają podciągi w tym wystąpieniu, które są rozdzielone przez co najmniej jeden znak w .separator Aby uzyskać więcej informacji, zobacz sekcję: Uwagi.

Wyjątki

count jest ujemna.

Przykłady

W poniższym przykładzie pokazano, jak count można użyć funkcji w celu ograniczenia liczby ciągów zwracanych przez Splitelement .

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"

Uwagi

Znaki ogranicznika nie są uwzględnione w elementach zwróconej tablicy.

Jeśli to wystąpienie nie zawiera żadnych znaków w separatorobiekcie , zwracana tablica składa się z jednego elementu zawierającego to wystąpienie. Jeśli count wartość jest równa zero, zwracana jest pusta tablica.

separator Jeśli parametr jest null lub nie zawiera znaków, przyjmuje się, że znaki odstępu są ogranicznikami. Znaki odstępu są definiowane przez standard Unicode, a Char.IsWhiteSpace metoda zwraca true wartość , jeśli zostaną do niej przekazane.

Każdy element definiuje separator oddzielny znak ogranicznika. Jeśli dwa ograniczniki są sąsiadujące lub ogranicznik znajduje się na początku lub na końcu tego wystąpienia, odpowiedni element tablicy zawiera Emptywartość .

Jeśli w tym wystąpieniu jest więcej niż count podciągów, pierwsze count - 1 podciągy są zwracane w pierwszych count - 1 elementach wartości zwracanej, a pozostałe znaki w tym wystąpieniu są zwracane w ostatnim elemecie zwracanej wartości.

Jeśli count jest większa niż liczba podciągów, dostępne podciągy są zwracane i nie jest zgłaszany żaden wyjątek.

W poniższej tabeli przedstawiono kilka przykładów.

Język Wartość ciągu Separator Zwracana tablica
C# "42, 12, 19" new Char[] {',', ' '} {"42", "", "12", "", "19"}
Visual Basic "42, 12, 19" Char() = {","c, " "c}) {"42", "", "12", "", "19"}
C# "42..12..19." nowy znak[] {'.'} {"42", "", "12", "", "19", ""}
Visual Basic "42..12..19." Char() = {"." c} {"42", "", "12", "", "19", ""}
C# "Banan" nowy znak[] {'.'} {"Banana"}
Visual Basic "Banan" Char() = {"." c} {"Banana"}
C# "Darb\nSmarba" nowy znak[] {} {"Darb", "Smarba"}
Visual Basic "Darb" & vbLf & "Smarba" Char() = {} {"Darb", "Smarba"}
C# "Darb\nSmarba" null {"Darb", "Smarba"}
Visual Basic "Darb" & vbLf & "Smarba" Nothing {"Darb", "Smarba"}

Zagadnienia dotyczące wydajności

Metody Split przydzielają pamięć dla zwróconego obiektu tablicy i String obiektu dla każdego elementu tablicy. Jeśli aplikacja wymaga optymalnej wydajności lub jeśli zarządzanie alokacją pamięci ma krytyczne znaczenie w aplikacji, rozważ użycie IndexOf metody lub IndexOfAny i opcjonalnie Compare metodę , aby zlokalizować podciąg w ciągu.

Jeśli dzielisz ciąg na znak separatora, użyj IndexOf metody lub IndexOfAny , aby zlokalizować znak separatora w ciągu. Jeśli dzielisz ciąg w ciągu separatora, użyj IndexOf metody lub IndexOfAny , aby zlokalizować pierwszy znak ciągu separatora. Następnie użyj Compare metody , aby określić, czy znaki po tym pierwszym znaku są równe pozostałym znakom ciągu separatora.

Ponadto, jeśli ten sam zestaw znaków jest używany do dzielenia ciągów w wielu Split wywołaniach metody, rozważ utworzenie pojedynczej tablicy i odwołanie do niej w każdym wywołaniu metody. Pozwala to znacznie ograniczyć dodatkowe obciążenie każdego wywołania metody.

Uwagi dotyczące wywoływania

W .NET Framework 3.5 i starszych wersjach, jeśli Split(Char[]) metoda jest przekazywana separatornull lub nie zawiera znaków, metoda używa nieco innego zestawu znaków odstępu, aby podzielić ciąg niż Trim(Char[]) metoda, aby przyciąć ciąg. Począwszy od .NET Framework 4, obie metody używają identycznego zestawu znaków odstępów Unicode.

Zobacz też

Dotyczy

Split(Char[], StringSplitOptions)

Dzieli ciąg na podciągi na podstawie określonych znaków i opcji ograniczeń.

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

Parametry

separator
Char[]

Tablica znaków rozdzielających podciągi w tym ciągu, pustą tablicę, która nie zawiera ograniczników ani null.

options
StringSplitOptions

Bitowa kombinacja wartości wyliczenia, która określa, czy przycinać podciągy i uwzględniać puste podciągy.

Zwraca

String[]

Tablica, której elementy zawierają podciągi w tym ciągu rozdzielone przez co najmniej jeden znak w separatorobiekcie . Aby uzyskać więcej informacji, zobacz sekcję: Uwagi.

Atrybuty

Wyjątki

options nie jest jedną z StringSplitOptions wartości.

Przykłady

W poniższym przykładzie użyto StringSplitOptions wyliczenia w celu uwzględnienia lub wykluczenia podciągów wygenerowanych przez metodę Split .

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

Uwagi

Znaki ogranicznika (znaki w tablicy separator ) nie są uwzględniane w elementach zwracanej tablicy. Jeśli na przykład tablica separator zawiera znak "-", a wartość bieżącego wystąpienia ciągu to "aa-bb-cc", metoda zwraca tablicę zawierającą trzy elementy: "aa", "bb" i "cc".

Jeśli to wystąpienie nie zawiera żadnych znaków w separatorobiekcie , zwracana tablica składa się z jednego elementu zawierającego to wystąpienie.

options Jeśli parametr ma wartość RemoveEmptyEntries , a długość tego wystąpienia wynosi zero, metoda zwraca pustą tablicę.

Każdy element definiuje separator oddzielny ogranicznik, który składa się z pojedynczego znaku. options Jeśli argument ma Nonewartość , a dwa ograniczniki są sąsiadujące lub ogranicznik znajduje się na początku lub na końcu tego wystąpienia, odpowiedni element tablicy zawiera String.Emptywartość . Jeśli na przykład separator zawiera dwa elementy i '-''_', wartość wystąpienia ciągu to "-_aa-_", a wartość argumentu options to None, metoda zwraca tablicę ciągów z następującymi pięcioma elementami:

  1. String.Empty, który reprezentuje pusty ciąg poprzedzający znak "-" w indeksie 0.

  2. String.Empty, który reprezentuje pusty ciąg między znakiem "-" w indeksie 0 i znakiem "_" w indeksie 1.

  3. "aa".

  4. String.Empty, który reprezentuje pusty ciąg, który następuje po znaku "-" w indeksie 4.

  5. String.Empty, który reprezentuje pusty ciąg, który następuje po znaku "_" w indeksie 5.

Tablica separatorów

separator Jeśli parametr jest null lub nie zawiera żadnych znaków, zakłada się, że znaki odstępu są ogranicznikami. Znaki odstępu są definiowane przez standard Unicode, a Char.IsWhiteSpace metoda zwraca true wartość , jeśli są do niej przekazywane.

Aby przekazać null parametr dla parametru char[] separator , należy wskazać typ null elementu , aby uściślić wywołanie z innych przeciążeń, takich jak Split(String[], StringSplitOptions). W poniższym przykładzie pokazano kilka sposobów na jednoznaczną identyfikację tego przeciążenia.

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)

Szczegóły porównania

Metoda Split wyodrębnia podciągi w tym ciągu, które są rozdzielane przez co najmniej jeden znak w parametrze separator i zwraca te podciągi jako elementy tablicy.

Metoda Split wyszukuje ograniczniki, wykonując porównania przy użyciu reguł sortowania uwzględniającego wielkość liter. Aby uzyskać więcej informacji na temat sortowania wyrazów, ciągów i porządkowych, zobacz wyliczenie System.Globalization.CompareOptions .

Zagadnienia dotyczące wydajności

Metody Split przydzielają pamięć dla zwracanego obiektu tablicy i String obiektu dla każdego elementu tablicy. Jeśli aplikacja wymaga optymalnej wydajności lub zarządzania alokacją pamięci jest krytyczna w aplikacji, rozważ użycie IndexOf metody lub IndexOfAny i opcjonalnie Compare metodę, aby zlokalizować podciąg w ciągu.

Jeśli dzielisz ciąg na znak separatora, użyj IndexOf metody or IndexOfAny , aby zlokalizować znak separatora w ciągu. Jeśli dzielisz ciąg w ciągu separatora, użyj IndexOf metody or IndexOfAny , aby zlokalizować pierwszy znak ciągu separatora. Następnie użyj Compare metody , aby określić, czy znaki po tym pierwszym znaku są równe pozostałym znakom ciągu separatora.

Ponadto jeśli ten sam zestaw znaków jest używany do dzielenia ciągów w wielu Split wywołaniach metody, rozważ utworzenie pojedynczej tablicy i odwoływanie się do niej w każdym wywołaniu metody. Pozwala to znacznie ograniczyć dodatkowe obciążenie każdego wywołania metody.

Uwagi dotyczące wywoływania

W .NET Framework 3.5 i starszych wersjach, jeśli Split(Char[]) metoda jest przekazywana separatornull lub nie zawiera znaków, metoda używa nieco innego zestawu znaków odstępu, aby podzielić ciąg niż Trim(Char[]) metoda, aby przyciąć ciąg. Począwszy od .NET Framework 4, obie metody używają identycznego zestawu znaków odstępów Unicode.

Dotyczy

Split(String, StringSplitOptions)

Dzieli ciąg na podciągy oparte na podanym separatorze ciągów.

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

Parametry

separator
String

Ciąg, który rozdziela podciągi w tym ciągu.

options
StringSplitOptions

Bitowa kombinacja wartości wyliczenia, która określa, czy przycinać podciągy i uwzględniać puste podciągy.

Zwraca

String[]

Tablica, której elementy zawierają podciągi z tego wystąpienia, które są rozdzielone przez separator.

Dotyczy

Split(String[], StringSplitOptions)

Dzieli ciąg na podciągi na podstawie określonego ciągu ogranicznika i opcjonalnie opcji.

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

Parametry

separator
String[]

Tablica ciągów, które rozdzielą podciągi w tym ciągu, pustą tablicę, która nie zawiera ograniczników ani null.

options
StringSplitOptions

Bitowa kombinacja wartości wyliczenia, która określa, czy przycinać podciągy i uwzględniać puste podciągy.

Zwraca

String[]

Tablica, której elementy zawierają podciągi w tym ciągu rozdzielone przez co najmniej jeden ciąg w elemecie separator. Aby uzyskać więcej informacji, zobacz sekcję: Uwagi.

Atrybuty

Wyjątki

options nie jest jedną z StringSplitOptions wartości.

Przykłady

Poniższy przykład ilustruje różnicę w tablicach zwracanych przez wywołanie metody ciągu String.Split(String[], StringSplitOptions) z parametrem options równym StringSplitOptions.None i 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'

W poniższym przykładzie zdefiniowano tablicę separatorów, które zawierają znaki interpunkcyjne i znaki odstępu. Przekazanie tej tablicy wraz z wartością StringSplitOptions.RemoveEmptyEntries metody Split(String[], StringSplitOptions) zwraca tablicę składającą się z pojedynczych wyrazów z ciągu.

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

Należy pamiętać, że metoda jest wywoływana z argumentem ustawionym options na StringSplitOptions.RemoveEmptyEntrieswartość . Zapobiega to włączeniu zwracanej tablicy z uwzględnieniem String.Empty wartości reprezentujących puste dopasowania podciągów między znakami interpunkcyjnymi i znakami odstępu.

Uwagi

Gdy ciąg jest rozdzielany przez znany zestaw ciągów, można użyć Split metody , aby oddzielić ją od podciągów.

Ciągi ograniczników nie są uwzględniane w elementach zwracanej tablicy. Jeśli na przykład tablica separator zawiera ciąg "--", a wartość bieżącego wystąpienia ciągu to "aa--bb--cc", metoda zwraca tablicę zawierającą trzy elementy: "aa", "bb" i "cc".

Jeśli to wystąpienie nie zawiera żadnego z ciągów w separatorelemecie , zwracana tablica składa się z jednego elementu zawierającego to wystąpienie.

options Jeśli parametr ma wartość RemoveEmptyEntries i długość tego wystąpienia wynosi zero, metoda zwraca pustą tablicę.

Każdy element definiuje separator oddzielny ogranicznik składający się z co najmniej jednego znaku. options Jeśli argument ma Nonewartość , a dwa ograniczniki są sąsiadujące lub ogranicznik zostanie znaleziony na początku lub na końcu tego wystąpienia, odpowiedni element tablicy zawiera String.Emptywartość . Jeśli na przykład separator zawiera dwa elementy, "-" i "_", wartość wystąpienia ciągu to "-_aa-_", a wartość argumentu options to None, metoda zwraca tablicę ciągów z następującymi pięcioma elementami:

  1. String.Empty, który reprezentuje pusty ciąg poprzedzający podciąg "-" w indeksie 0.

  2. String.Empty, który reprezentuje pusty ciąg między podciągem "-" w indeksie 0 i podciągem "_" w indeksie 1.

  3. "aa".

  4. String.Empty, który reprezentuje pusty ciąg, który jest zgodny z podciągem "-" w indeksie 4.

  5. String.Empty, który reprezentuje pusty ciąg, który jest zgodny z podciągem "_" w indeksie 5.

Tablica separatorów

Jeśli którykolwiek z elementów w pliku separator składa się z wielu znaków, cały podciąg jest uważany za ogranicznik. Jeśli na przykład jeden z elementów w pliku separator to "10", próba podzielenia ciągu "This10is10a10string" zwraca następującą tablicę czteroelementową: { "This", "is", "a", "string". }.

separator Jeśli parametr jest null lub nie zawiera ciągów innych niż puste, zakłada się, że znaki odstępu są ogranicznikami. Znaki odstępu są definiowane przez standard Unicode, a Char.IsWhiteSpace metoda zwraca true wartość , jeśli są do niej przekazywane.

Aby przekazać null parametr dla parametru string[] separator , należy wskazać typ null elementu , aby uściślić wywołanie z innych przeciążeń, takich jak Split(Char[], StringSplitOptions). W poniższym przykładzie pokazano kilka sposobów na jednoznaczną identyfikację tego przeciążenia.

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)

Szczegóły porównania

Metoda Split wyodrębnia podciągi w tym ciągu, które są rozdzielane przez co najmniej jeden ciąg w parametrze separator i zwraca te podciągi jako elementy tablicy.

Metoda Split wyszukuje ograniczniki, wykonując porównania przy użyciu reguł sortowania uwzględniającego wielkość liter. Aby uzyskać więcej informacji na temat sortowania wyrazów, ciągów i porządkowych, zobacz wyliczenie System.Globalization.CompareOptions .

Metoda Split ignoruje dowolny element, którego separator wartość to null lub pusty ciąg ("").

Aby uniknąć niejednoznacznych wyników, gdy ciągi w separator postaci znaków są wspólne, Split operacja następuje od początku do końca wartości wystąpienia i odpowiada pierwszemu elementowi w separator tym, który jest równy ogranicznikowi w wystąpieniu. Kolejność napotkania podciągów w wystąpieniu ma pierwszeństwo przed kolejnością elementów w elemencie separator.

Rozważmy na przykład wystąpienie, którego wartość to "abcdef". Jeśli pierwszy element w separator pliku to "ef", a drugi element to "bcde", wynikiem operacji podziału będzie tablica ciągów zawierająca dwa elementy: "a" i "f". Dzieje się tak, ponieważ podciąg w wystąpieniu "bcde" występuje i pasuje do elementu przed separator napotkaniem podciągu "f".

Jeśli jednak pierwszy element to "bcd", a drugi element to "bc", wynikiem operacji podziału będzie tablica ciągów separator zawierająca dwa elementy: "a" i "ef". Jest to spowodowane tym, że "bcd" jest pierwszym ogranicznikiem w separator tym, który pasuje do ogranicznika w wystąpieniu. Jeśli kolejność separatorów została odwrócona, więc pierwszy element to "bc", a drugi element to "bcd", wynik będzie tablicą ciągów zawierającą dwa elementy: "a" i "def".

Zagadnienia dotyczące wydajności

Metody Split przydzielają pamięć dla zwracanego obiektu tablicy i String obiektu dla każdego elementu tablicy. Jeśli aplikacja wymaga optymalnej wydajności lub zarządzania alokacją pamięci jest krytyczna w aplikacji, rozważ użycie IndexOf metody lub IndexOfAny i opcjonalnie Compare metodę, aby zlokalizować podciąg w ciągu.

Jeśli dzielisz ciąg na znak separatora, użyj IndexOf metody or IndexOfAny , aby zlokalizować znak separatora w ciągu. Jeśli dzielisz ciąg w ciągu separatora, użyj IndexOf metody or IndexOfAny , aby zlokalizować pierwszy znak ciągu separatora. Następnie użyj Compare metody , aby określić, czy znaki po tym pierwszym znaku są równe pozostałym znakom ciągu separatora.

Ponadto jeśli ten sam zestaw znaków jest używany do dzielenia ciągów w wielu Split wywołaniach metody, rozważ utworzenie pojedynczej tablicy i odwoływanie się do niej w każdym wywołaniu metody. Pozwala to znacznie ograniczyć dodatkowe obciążenie każdego wywołania metody.

Uwagi dotyczące wywoływania

W .NET Framework 3.5 i starszych wersjach, jeśli Split(Char[]) metoda jest przekazywana separatornull lub nie zawiera znaków, metoda używa nieco innego zestawu znaków odstępu, aby podzielić ciąg niż Trim(Char[]) metoda, aby przyciąć ciąg. Począwszy od .NET Framework 4, obie metody używają identycznego zestawu znaków znaków unicode.

Dotyczy

Split(Char, Int32, StringSplitOptions)

Dzieli ciąg na maksymalną liczbę podciągów na podstawie określonego znaku ogranicznika i opcjonalnie opcji. Dzieli ciąg na maksymalną liczbę podciągów na podstawie podanego separatora znaków, opcjonalnie pomijając puste podciągnięcia z wyniku.

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

Parametry

separator
Char

Znak, który rozdziela podciągi w tym wystąpieniu.

count
Int32

Maksymalna liczba elementów oczekiwana w tablicy.

options
StringSplitOptions

Bitowa kombinacja wartości wyliczenia, która określa, czy przycinać podciągy i uwzględniać puste podciągy.

Zwraca

String[]

Tablica zawierająca w większości count podciągów z tego wystąpienia, które są rozdzielane przez separatorelement .

Uwagi

Jeśli ciąg został już podzielony count — 1 razy, ale koniec ciągu nie został osiągnięty, ostatni ciąg w zwróconej tablicy będzie zawierać pozostałe końcowe podciąg tego wystąpienia, nietknięte.

Dotyczy

Split(Char[], Int32, StringSplitOptions)

Dzieli ciąg na maksymalną liczbę podciągów na podstawie określonych znaków ograniczników i, opcjonalnie, opcji.

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

Parametry

separator
Char[]

Tablica znaków, która rozdziela podciąg w tym ciągu, pustą tablicę, która nie zawiera ograniczników ani null.

count
Int32

Maksymalna liczba podciągów do zwrócenia.

options
StringSplitOptions

Bitowa kombinacja wartości wyliczenia, która określa, czy przycinać podciągy i uwzględniać puste podciągy.

Zwraca

String[]

Tablica zawierająca podciągi w tym ciągu, które są rozdzielone przez co najmniej jeden znak w pliku separator. Aby uzyskać więcej informacji, zobacz sekcję: Uwagi.

Atrybuty

Wyjątki

count jest ujemna.

options nie jest jedną z StringSplitOptions wartości.

Przykłady

W poniższym przykładzie użyto wyliczenia StringSplitOptions do uwzględnienia lub wykluczenia podciągów wygenerowanych przez metodę Split .

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

Uwagi

Znaki ogranicznika nie są uwzględnione w elementach zwróconej tablicy.

Jeśli to wystąpienie nie zawiera żadnego znaku w separatorobiekcie lub count parametr ma wartość 1, zwracana tablica składa się z jednego elementu zawierającego to wystąpienie.

separator Jeśli parametr jest null lub nie zawiera żadnych znaków, zakłada się, że znaki odstępu są ogranicznikami. Znaki odstępu są definiowane przez standard Unicode, a Char.IsWhiteSpace metoda zwraca true wartość , jeśli są do niej przekazywane.

Aby przekazać null parametr dla parametru char[] separator , należy wskazać typ null elementu , aby uściślić wywołanie z innych przeciążeń, takich jak Split(String[], Int32, StringSplitOptions). W poniższym przykładzie pokazano kilka sposobów na jednoznaczną identyfikację tego przeciążenia.

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)

count Jeśli parametr ma wartość zero lub options parametr jest RemoveEmptyEntries i długość tego wystąpienia wynosi zero, zwracana jest pusta tablica.

Każdy element definiuje separator oddzielny znak ogranicznika. options Jeśli parametr ma Nonewartość , a dwa ograniczniki są sąsiadujące lub ogranicznik znajduje się na początku lub na końcu tego wystąpienia, odpowiedni element tablicy zawiera Emptywartość .

Jeśli w tym wystąpieniu jest więcej niż count podciągów, pierwsze count podciąg minus 1 są zwracane w pierwszym count minus 1 elementach wartości zwracanej, a pozostałe znaki w tym wystąpieniu są zwracane w ostatnim elemecie wartości zwracanej.

Jeśli count jest większa niż liczba podciągów, dostępne podciągy są zwracane i nie jest zgłaszany żaden wyjątek.

Zagadnienia dotyczące wydajności

Metody Split przydzielają pamięć dla zwróconego obiektu tablicy i String obiektu dla każdego elementu tablicy. Jeśli aplikacja wymaga optymalnej wydajności lub jeśli zarządzanie alokacją pamięci ma krytyczne znaczenie w aplikacji, rozważ użycie IndexOf metody lub IndexOfAny i opcjonalnie Compare metodę , aby zlokalizować podciąg w ciągu.

Jeśli dzielisz ciąg na znak separatora, użyj IndexOf metody lub IndexOfAny , aby zlokalizować znak separatora w ciągu. Jeśli dzielisz ciąg w ciągu separatora, użyj IndexOf metody lub IndexOfAny , aby zlokalizować pierwszy znak ciągu separatora. Następnie użyj Compare metody , aby określić, czy znaki po tym pierwszym znaku są równe pozostałym znakom ciągu separatora.

Ponadto, jeśli ten sam zestaw znaków jest używany do dzielenia ciągów w wielu Split wywołaniach metody, rozważ utworzenie pojedynczej tablicy i odwołanie do niej w każdym wywołaniu metody. Pozwala to znacznie ograniczyć dodatkowe obciążenie każdego wywołania metody.

Uwagi dotyczące wywoływania

W .NET Framework 3.5 i starszych wersjach, jeśli Split(Char[]) metoda jest przekazywana separatornull lub nie zawiera znaków, metoda używa nieco innego zestawu znaków odstępu, aby podzielić ciąg niż Trim(Char[]) metoda, aby przyciąć ciąg. Począwszy od .NET Framework 4, obie metody używają identycznego zestawu znaków znaków unicode.

Dotyczy

Split(String, Int32, StringSplitOptions)

Dzieli ciąg na maksymalną liczbę podciągów na podstawie określonego ciągu ogranicznika i opcjonalnie opcji.

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

Parametry

separator
String

Ciąg, który rozdziela podciągi w tym wystąpieniu.

count
Int32

Maksymalna liczba elementów oczekiwanych w tablicy.

options
StringSplitOptions

Bitowa kombinacja wartości wyliczenia, która określa, czy przycinać podciągy i uwzględniać puste podciągy.

Zwraca

String[]

Tablica zawierająca najwyżej count podciągi z tego wystąpienia, które są rozdzielane przez separator.

Uwagi

Jeśli ciąg został już podzielony count — 1 razy, ale koniec ciągu nie został osiągnięty, ostatni ciąg w zwróconej tablicy będzie zawierać pozostałe końcowe podciąg tego wystąpienia, nietknięty.

Dotyczy

Split(String[], Int32, StringSplitOptions)

Dzieli ciąg na maksymalną liczbę podciągów na podstawie określonych ciągów ograniczników i opcjonalnie opcji.

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

Parametry

separator
String[]

Ciągi rozdzielające podciągi w tym ciągu, pustą tablicę, która nie zawiera ograniczników ani null.

count
Int32

Maksymalna liczba podciągów do zwrócenia.

options
StringSplitOptions

Bitowa kombinacja wartości wyliczenia, która określa, czy przycinać podciągy i uwzględniać puste podciągy.

Zwraca

String[]

Tablica, której elementy zawierają podciągi w tym ciągu, które są rozdzielone przez jeden lub więcej ciągów w elemecie separator. Aby uzyskać więcej informacji, zobacz sekcję: Uwagi.

Atrybuty

Wyjątki

count jest ujemna.

options nie jest jedną z StringSplitOptions wartości.

Przykłady

W poniższym przykładzie użyto StringSplitOptions wyliczenia w celu uwzględnienia lub wykluczenia podciągów wygenerowanych przez metodę Split .

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

Uwagi

Ciągi ograniczników nie są uwzględniane w elementach zwracanej tablicy.

Jeśli to wystąpienie nie zawiera żadnych ciągów w separatorelemecie , lub count parametr ma wartość 1, zwracana tablica składa się z jednego elementu zawierającego to wystąpienie.

separator Jeśli parametr jest null lub nie zawiera znaków, przyjmuje się, że znaki odstępu są ogranicznikami. Znaki odstępu są definiowane przez standard Unicode, a Char.IsWhiteSpace metoda zwraca true wartość , jeśli zostaną do niej przekazane.

Aby przekazać null parametr string[] separator , należy wskazać typ null metody , aby uściślić wywołanie z innych przeciążeń, takich jak Split(Char[], Int32, StringSplitOptions). W poniższym przykładzie pokazano kilka sposobów na jednoznaczną identyfikację tego przeciążenia.

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)

count Jeśli parametr ma wartość zero lub options parametr ma RemoveEmptyEntries wartość , a długość tego wystąpienia wynosi zero, zwracana jest pusta tablica.

Każdy element definiuje separator oddzielny ogranicznik, który składa się z co najmniej jednego znaku. options Jeśli parametr ma Nonewartość , a dwa ograniczniki są sąsiadujące lub ogranicznik znajduje się na początku lub na końcu tego wystąpienia, odpowiedni element tablicy zawiera Emptywartość .

Jeśli w tym wystąpieniu jest więcej niż count podciągów, pierwsze count podciąg minus 1 są zwracane w pierwszym count minus 1 elementach wartości zwracanej, a pozostałe znaki w tym wystąpieniu są zwracane w ostatnim elemecie wartości zwracanej.

Jeśli count jest większa niż liczba podciągów, dostępne podciągy są zwracane i nie jest zgłaszany żaden wyjątek.

Tablica separatorów

Jeśli którykolwiek z elementów w obiekcie separator składa się z wielu znaków, cały podciąg jest uważany za ogranicznik. Jeśli na przykład jeden z elementów w obiekcie separator to "10", próba podzielenia ciągu "This10is10a10string". Zwraca tę tablicę czteroelementową: { "This", "is", "a", "string". }.

Szczegóły porównania

Metoda Split wyodrębnia podciągi w tym ciągu, które są rozdzielane przez co najmniej jeden ciąg w parametrze separator i zwraca te podciągi jako elementy tablicy.

Metoda Split wyszukuje ograniczniki, wykonując porównania przy użyciu reguł sortowania porządkowego uwzględniających wielkość liter. Aby uzyskać więcej informacji na temat sortowania wyrazów, ciągów i porządkowych, zobacz System.Globalization.CompareOptions wyliczenie.

Metoda Split ignoruje dowolny element, którego separator wartość jest null lub pusty ciąg ("").

Aby uniknąć niejednoznacznych wyników, gdy ciągi w separator znakach są wspólne, Split metoda przechodzi od początku do końca wartości wystąpienia i pasuje do pierwszego elementu w separator tym jest równy ogranicznikowi w wystąpieniu. Kolejność napotkania podciągów w wystąpieniu ma pierwszeństwo przed kolejnością elementów w elemencie separator.

Rozważmy na przykład wystąpienie, którego wartość to "abcdef". Jeśli pierwszy element w pliku separator to "ef", a drugi element to "bcde", wynikiem operacji podziału będzie "a" i "f". Dzieje się tak, ponieważ napotkano podciąg w wystąpieniu "bcde" i pasuje do elementu przed separator napotkaniem podciągów "f".

Jeśli jednak pierwszy element separator elementu to "bcd", a drugi element to "bc", wynikiem operacji podziału będzie "a" i "ef". Jest to spowodowane tym, że "bcd" jest pierwszym ogranicznikiem w separator tym, który pasuje do ogranicznika w wystąpieniu. Jeśli kolejność separatorów została odwrócona, więc pierwszy element to "bc", a drugi element to "bcd", wynikiem będzie "a" i "def".

Zagadnienia dotyczące wydajności

Metody Split przydzielają pamięć dla zwróconego obiektu tablicy i String obiektu dla każdego elementu tablicy. Jeśli aplikacja wymaga optymalnej wydajności lub jeśli zarządzanie alokacją pamięci ma krytyczne znaczenie w aplikacji, rozważ użycie IndexOf metody lub IndexOfAny i opcjonalnie Compare metodę , aby zlokalizować podciąg w ciągu.

Jeśli dzielisz ciąg na znak separatora, użyj IndexOf metody lub IndexOfAny , aby zlokalizować znak separatora w ciągu. Jeśli dzielisz ciąg w ciągu separatora, użyj IndexOf metody lub IndexOfAny , aby zlokalizować pierwszy znak ciągu separatora. Następnie użyj Compare metody , aby określić, czy znaki po tym pierwszym znaku są równe pozostałym znakom ciągu separatora.

Ponadto, jeśli ten sam zestaw znaków jest używany do dzielenia ciągów w wielu Split wywołaniach metody, rozważ utworzenie pojedynczej tablicy i odwołanie do niej w każdym wywołaniu metody. Pozwala to znacznie ograniczyć dodatkowe obciążenie każdego wywołania metody.

Uwagi dotyczące wywoływania

W .NET Framework 3.5 i starszych wersjach, jeśli Split(Char[]) metoda jest przekazywana separatornull lub nie zawiera znaków, metoda używa nieco innego zestawu znaków odstępu, aby podzielić ciąg niż Trim(Char[]) metoda, aby przyciąć ciąg. Począwszy od .NET Framework 4, obie metody używają identycznego zestawu znaków odstępów Unicode.

Dotyczy