Бөлісу құралы:


String.Split Метод

Определение

Возвращает массив строк, содержащий подстроки в этом экземпляре, разделенные элементами указанной строки или массива символов Юникода.

Перегрузки

Имя Описание
Split(Rune, StringSplitOptions)
Split(String[], Int32, StringSplitOptions)

Разбивает строку на максимальное количество подстроок на основе указанных строк разделителя и, при необходимости, параметров.

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

Разбивает строку на максимальное количество подстроок на основе указанных символов разделителя и, при необходимости, параметров.

Split(Char, Int32, StringSplitOptions)

Разбивает строку на максимальное количество подстроок на основе предоставленного разделителя символов, при необходимости пропуская пустые подстроки из результата.

Split(String[], StringSplitOptions)

Разбивает строку на подстроки на основе указанной строки разделителя и, при необходимости, параметров.

Split(String, Int32, StringSplitOptions)

Разбивает строку на максимальное количество подстроок на основе указанной строки разделителя и, при необходимости, параметров.

Split(Char[], StringSplitOptions)

Разбивает строку на подстроки на основе указанных символов и параметров разделителя.

Split(Char[], Int32)

Разбивает строку на максимальное количество подстроок на основе указанных символов разделителей.

Split(Char, StringSplitOptions)

Разбивает строку на подстроки на основе указанного символа разделителя и, при необходимости, параметров.

Split(ReadOnlySpan<Char>)

Разбивает строку на подстроки на основе указанных символов разделителей.

Split(Char[])

Разбивает строку на подстроки на основе указанных символов разделителей.

Split(String, StringSplitOptions)

Разбивает строку на подстроки, основанные на предоставленном разделитетеле строк.

Комментарии

Split используется для разрыва строки с разделителями на подстроки. Можно использовать массив символов или строковый массив, чтобы указать ноль или больше символов разделителя или строк. Если символы разделителя не указаны, строка разбивается на пробелы.

Перегрузки Split метода позволяют ограничить количество подстроок, возвращаемых методом (методом), чтобы указать, следует ли включать пустые строки и /или обрезать подстроки в результат ( Split(Char[], Int32)Split(Char[], StringSplitOptions) и Split(String[], StringSplitOptions) методы) или выполнять оба Split(Char[], Int32, StringSplitOptions)Split(String[], Int32, StringSplitOptions) методы).

Кончик

Метод Split не всегда является лучшим способом разбить строку с разделителями на подстроки. Если вы не хотите извлекать все подстроки строки с разделителями, или если вы хотите проанализировать строку на основе шаблона вместо набора символов разделителя, попробуйте использовать регулярные выражения или объединить один из методов поиска, возвращающих индекс символа с Substring методом. Дополнительные сведения см. в разделе "Извлечение подстроок" из строки.

Пример

Ниже показаны три различные перегрузки String.Split(). В первом примере вызывается перегрузка Split(Char[]) и передается в один разделитель.

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.

Как видите, символы-точки (.) содержатся в двух подстроках. Если вы хотите исключить символы периода, можно добавить символ периода в качестве дополнительного символа разделителя. В следующем примере показано, как это сделать.

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:

Периоды исчезли из подстроок, но теперь были включены две дополнительные пустые подстроки. Эти пустые подстроки представляют подстроку между словом и периодом, который следует за ним. Чтобы исключить из результирующего массива пустые подстроки, вызовите перегрузку Split(Char[], StringSplitOptions) и укажите StringSplitOptions.RemoveEmptyEntries для параметра 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

Разделы для отдельных String.Split() перегрузок содержат дополнительные примеры.

Split(Rune, StringSplitOptions)

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

Параметры

separator
Rune

Возвращаемое значение

String[]

Применяется к

Split(String[], Int32, StringSplitOptions)

Исходный код:
String.Manipulation.cs
Исходный код:
String.Manipulation.cs
Исходный код:
String.Manipulation.cs
Исходный код:
String.Manipulation.cs

Разбивает строку на максимальное количество подстроок на основе указанных строк разделителя и, при необходимости, параметров.

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

Параметры

separator
String[]

Строки, разделяющие подстроки в этой строке, пустой массив, который не содержит разделителей или null.

count
Int32

Максимальное количество возвращаемых подстроок.

options
StringSplitOptions

Побитовое сочетание значений перечисления, указывающее, следует ли обрезать подстроки и включать пустые подстроки.

Возвращаемое значение

String[]

Массив, элементы которого содержат подстроки в этой строке, разделенные одной или несколькими строками.separator Дополнительные сведения см. в разделе "Примечания".

Атрибуты

Исключения

count является отрицательным.

options не является одним из значений StringSplitOptions .

Примеры

В следующем примере перечисление StringSplitOptions используется для включения или исключения подстроок, созданных методом Split .

// This example demonstrates the String.Split() methods that use
// the StringSplitOptions enumeration.

// Example 1: Split a string delimited by characters
Console.WriteLine("1) Split a string delimited by characters:\n");

string s1 = ",ONE,, TWO,, , THREE,,";
char[] charSeparators = new char[] { ',' };
string[] result;

Console.WriteLine($"The original string is: \"{s1}\".");
Console.WriteLine($"The delimiter character is: '{charSeparators[0]}'.\n");

// Split the string and return all elements
Console.WriteLine("1a) Return all elements:");
result = s1.Split(charSeparators, StringSplitOptions.None);
Show(result);

// Split the string and return all elements with whitespace trimmed
Console.WriteLine("1b) Return all elements with whitespace trimmed:");
result = s1.Split(charSeparators, StringSplitOptions.TrimEntries);
Show(result);

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

// Split the string and return all non-whitespace elements with whitespace trimmed
Console.WriteLine("1d) Return all non-whitespace elements with whitespace trimmed:");
result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
Show(result);


// Split the string into only two elements, keeping the remainder in the last match
Console.WriteLine("1e) Split into only two elements:");
result = s1.Split(charSeparators, 2, StringSplitOptions.None);
Show(result);

// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("1f) Split into only two elements with whitespace trimmed:");
result = s1.Split(charSeparators, 2, StringSplitOptions.TrimEntries);
Show(result);

// Split the string into only two non-empty elements, keeping the remainder in the last match
Console.WriteLine("1g) Split into only two non-empty elements:");
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries);
Show(result);

// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("1h) Split into only two non-whitespace elements with whitespace trimmed:");
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
Show(result);


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

string s2 = "[stop]" +
            "ONE[stop] [stop]" +
            "TWO  [stop][stop]  [stop]" +
            "THREE[stop][stop]  ";
string[] stringSeparators = new string[] { "[stop]" };

Console.WriteLine($"The original string is: \"{s2}\".");
Console.WriteLine($"The delimiter string is: \"{stringSeparators[0]}\".\n");

// Split the string and return all elements
Console.WriteLine("2a) Return all elements:");
result = s2.Split(stringSeparators, StringSplitOptions.None);
Show(result);

// Split the string and return all elements with whitespace trimmed
Console.WriteLine("2b) Return all elements with whitespace trimmed:");
result = s2.Split(stringSeparators, StringSplitOptions.TrimEntries);
Show(result);

// Split the string and return all non-empty elements
Console.WriteLine("2c) Return all non-empty elements:");
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);
Show(result);

// Split the string and return all non-whitespace elements with whitespace trimmed
Console.WriteLine("2d) Return all non-whitespace elements with whitespace trimmed:");
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
Show(result);


// Split the string into only two elements, keeping the remainder in the last match
Console.WriteLine("2e) Split into only two elements:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.None);
Show(result);

// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("2f) Split into only two elements with whitespace trimmed:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.TrimEntries);
Show(result);

// Split the string into only two non-empty elements, keeping the remainder in the last match
Console.WriteLine("2g) Split into only two non-empty elements:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries);
Show(result);

// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("2h) Split into only two non-whitespace elements with whitespace trimmed:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
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:

The original string is: ",ONE,, TWO,, , THREE,,".
The delimiter character is: ','.

1a) Return all elements:
The return value contains these 9 elements:
<><ONE><>< TWO><>< >< THREE><><>

1b) Return all elements with whitespace trimmed:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>

1c) Return all non-empty elements:
The return value contains these 4 elements:
<ONE>< TWO>< >< THREE>

1d) Return all non-whitespace elements with whitespace trimmed:
The return value contains these 3 elements:
<ONE><TWO><THREE>

1e) Split into only two elements:
The return value contains these 2 elements:
<><ONE,, TWO,, , THREE,,>

1f) Split into only two elements with whitespace trimmed:
The return value contains these 2 elements:
<><ONE,, TWO,, , THREE,,>

1g) Split into only two non-empty elements:
The return value contains these 2 elements:
<ONE>< TWO,, , THREE,,>

1h) Split into only two non-whitespace elements with whitespace trimmed:
The return value contains these 2 elements:
<ONE><TWO,, , THREE,,>

2) Split a string delimited by another string:

The original string is: "[stop]ONE[stop] [stop]TWO  [stop][stop]  [stop]THREE[stop][stop]  ".
The delimiter string is: "[stop]".

2a) Return all elements:
The return value contains these 9 elements:
<><ONE>< ><TWO  ><><  ><THREE><><  >

2b) Return all elements with whitespace trimmed:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>

2c) Return all non-empty elements:
The return value contains these 6 elements:
<ONE>< ><TWO  ><  ><THREE><  >

2d) Return all non-whitespace elements with whitespace trimmed:
The return value contains these 3 elements:
<ONE><TWO><THREE>

2e) Split into only two elements:
The return value contains these 2 elements:
<><ONE[stop] [stop]TWO  [stop][stop]  [stop]THREE[stop][stop]  >

2f) Split into only two elements with whitespace trimmed:
The return value contains these 2 elements:
<><ONE[stop] [stop]TWO  [stop][stop]  [stop]THREE[stop][stop]>

2g) Split into only two non-empty elements:
The return value contains these 2 elements:
<ONE>< [stop]TWO  [stop][stop]  [stop]THREE[stop][stop]  >

2h) Split into only two non-whitespace elements with whitespace trimmed:
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"

// Example 1: Split a string delimited by characters
printfn "1) Split a string delimited by characters:\n"

let s1 = ",ONE,, TWO,, , THREE,,"
let charSeparators = [| ',' |]

printfn $"The original string is: \"{s1}\"."
printfn $"The delimiter character is: '{charSeparators[0]}'.\n"

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

// Split the string and return all elements with whitespace trimmed
printfn "1b) Return all elements with whitespace trimmed:"
let result = s1.Split(charSeparators, StringSplitOptions.TrimEntries)
show result

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

// Split the string and return all non-whitespace elements with whitespace trimmed
printfn "1d) Return all non-whitespace elements with whitespace trimmed:"
let result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)
show result


// Split the string into only two elements, keeping the remainder in the last match
printfn "1e) Split into only two elements:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.None)
show result

// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
printfn "1f) Split into only two elements with whitespace trimmed:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.TrimEntries)
show result

// Split the string into only two non-empty elements, keeping the remainder in the last match
printfn "1g) Split into only two non-empty elements:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
show result

// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
printfn "1h) Split into only two non-whitespace elements with whitespace trimmed:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)
show result


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

let s2 = "[stop]" +
            "ONE[stop] [stop]" +
            "TWO  [stop][stop]  [stop]" +
            "THREE[stop][stop]  "
let stringSeparators = [| "[stop]" |]

printfn $"The original string is: \"{s2}\"."
printfn $"The delimiter string is: \"{stringSeparators[0]}\".\n"

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

// Split the string and return all elements with whitespace trimmed
printfn "2b) Return all elements with whitespace trimmed:"
let result = s2.Split(stringSeparators, StringSplitOptions.TrimEntries)
show result

// Split the string and return all non-empty elements
printfn "2c) Return all non-empty elements:"
let result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)
show result

// Split the string and return all non-whitespace elements with whitespace trimmed
printfn "2d) Return all non-whitespace elements with whitespace trimmed:"
let result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)
show result


// Split the string into only two elements, keeping the remainder in the last match
printfn "2e) Split into only two elements:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.None)
show result

// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
printfn "2f) Split into only two elements with whitespace trimmed:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.TrimEntries)
show result

// Split the string into only two non-empty elements, keeping the remainder in the last match
printfn "2g) Split into only two non-empty elements:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
show result

// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
printfn "2h) Split into only two non-whitespace elements with whitespace trimmed:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)
show result

(*
This example produces the following results:

1) Split a string delimited by characters:

The original string is: ",ONE,, TWO,, , THREE,,".
The delimiter character is: ','.

1a) Return all elements:
The return value contains these 9 elements:
<><ONE><>< TWO><>< >< THREE><><>

1b) Return all elements with whitespace trimmed:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>

1c) Return all non-empty elements:
The return value contains these 4 elements:
<ONE>< TWO>< >< THREE>

1d) Return all non-whitespace elements with whitespace trimmed:
The return value contains these 3 elements:
<ONE><TWO><THREE>

1e) Split into only two elements:
The return value contains these 2 elements:
<><ONE,, TWO,, , THREE,,>

1f) Split into only two elements with whitespace trimmed:
The return value contains these 2 elements:
<><ONE,, TWO,, , THREE,,>

1g) Split into only two non-empty elements:
The return value contains these 2 elements:
<ONE>< TWO,, , THREE,,>

1h) Split into only two non-whitespace elements with whitespace trimmed:
The return value contains these 2 elements:
<ONE><TWO,, , THREE,,>

2) Split a string delimited by another string:

The original string is: "[stop]ONE[stop] [stop]TWO  [stop][stop]  [stop]THREE[stop][stop]  ".
The delimiter string is: "[stop]".

2a) Return all elements:
The return value contains these 9 elements:
<><ONE>< ><TWO  ><><  ><THREE><><  >

2b) Return all elements with whitespace trimmed:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>

2c) Return all non-empty elements:
The return value contains these 6 elements:
<ONE>< ><TWO  ><  ><THREE><  >

2d) Return all non-whitespace elements with whitespace trimmed:
The return value contains these 3 elements:
<ONE><TWO><THREE>

2e) Split into only two elements:
The return value contains these 2 elements:
<><ONE[stop] [stop]TWO  [stop][stop]  [stop]THREE[stop][stop]  >

2f) Split into only two elements with whitespace trimmed:
The return value contains these 2 elements:
<><ONE[stop] [stop]TWO  [stop][stop]  [stop]THREE[stop][stop]>

2g) Split into only two non-empty elements:
The return value contains these 2 elements:
<ONE>< [stop]TWO  [stop][stop]  [stop]THREE[stop][stop]  >

2h) Split into only two non-whitespace elements with whitespace trimmed:
The return value contains these 2 elements:
<ONE><TWO  [stop][stop]  [stop]THREE[stop][stop]>

*)
Public Shared Sub StringSplitOptionsExamples()
    ' This example demonstrates the String.Split() methods that use
    ' the StringSplitOptions enumeration.

    ' Example 1: Split a string delimited by characters
    Console.WriteLine("1) Split a string delimited by characters:" & vbCrLf)

    Dim s1 As String = ",ONE,, TWO,, , THREE,,"
    Dim charSeparators() As Char = {","c}
    Dim result() As String

    Console.WriteLine("The original string is: ""{0}"".", s1)
    Console.WriteLine("The delimiter character is: '{0}'." & vbCrLf, charSeparators(0))

    ' Split the string and return all elements
    Console.WriteLine("1a) Return all elements:")
    result = s1.Split(charSeparators, StringSplitOptions.None)
    Show(result)

    ' Split the string and return all elements with whitespace trimmed
    Console.WriteLine("1b) Return all elements with whitespace trimmed:")
    result = s1.Split(charSeparators, StringSplitOptions.TrimEntries)
    Show(result)

    ' Split the string and return all non-empty elements
    Console.WriteLine("1c) Return all non-empty elements:")
    result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries)
    Show(result)

    ' Split the string and return all non-whitespace elements with whitespace trimmed
    Console.WriteLine("1d) Return all non-whitespace elements with whitespace trimmed:")
    result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries)
    Show(result)


    ' Split the string into only two elements, keeping the remainder in the last match
    Console.WriteLine("1e) Split into only two elements:")
    result = s1.Split(charSeparators, 2, StringSplitOptions.None)
    Show(result)

    ' Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
    Console.WriteLine("1f) Split into only two elements with whitespace trimmed:")
    result = s1.Split(charSeparators, 2, StringSplitOptions.TrimEntries)
    Show(result)

    ' Split the string into only two non-empty elements, keeping the remainder in the last match
    Console.WriteLine("1g) Split into only two non-empty elements:")
    result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
    Show(result)

    ' Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
    Console.WriteLine("1h) Split into only two non-whitespace elements with whitespace trimmed:")
    result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries)
    Show(result)


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

    Dim s2 As String = "[stop]" +
                "ONE[stop] [stop]" +
                "TWO  [stop][stop]  [stop]" +
                "THREE[stop][stop]  "
    Dim stringSeparators() As String = {"[stop]"}


    Console.WriteLine("The original string is: ""{0}"".", s2)
    Console.WriteLine("The delimiter string is: ""{0}""." & vbCrLf, stringSeparators(0))

    ' Split the string and return all elements
    Console.WriteLine("2a) Return all elements:")
    result = s2.Split(stringSeparators, StringSplitOptions.None)
    Show(result)

    ' Split the string and return all elements with whitespace trimmed
    Console.WriteLine("2b) Return all elements with whitespace trimmed:")
    result = s2.Split(stringSeparators, StringSplitOptions.TrimEntries)
    Show(result)

    ' Split the string and return all non-empty elements
    Console.WriteLine("2c) Return all non-empty elements:")
    result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)
    Show(result)

    ' Split the string and return all non-whitespace elements with whitespace trimmed
    Console.WriteLine("2d) Return all non-whitespace elements with whitespace trimmed:")
    result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries)
    Show(result)


    ' Split the string into only two elements, keeping the remainder in the last match
    Console.WriteLine("2e) Split into only two elements:")
    result = s2.Split(stringSeparators, 2, StringSplitOptions.None)
    Show(result)

    ' Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
    Console.WriteLine("2f) Split into only two elements with whitespace trimmed:")
    result = s2.Split(stringSeparators, 2, StringSplitOptions.TrimEntries)
    Show(result)

    ' Split the string into only two non-empty elements, keeping the remainder in the last match
    Console.WriteLine("2g) Split into only two non-empty elements:")
    result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
    Show(result)

    ' Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
    Console.WriteLine("2h) Split into only two non-whitespace elements with whitespace trimmed:")
    result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries)
    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:
'
' The original string is: ",ONE,, TWO,, , THREE,,".
' The delimiter character is: ','.
'
' 1a) Return all elements:
' The return value contains these 9 elements:
' <><ONE><>< TWO><>< >< THREE><><>
'
' 1b) Return all elements with whitespace trimmed:
' The return value contains these 9 elements:
' <><ONE><><TWO><><><THREE><><>
'
' 1c) Return all non-empty elements:
' The return value contains these 4 elements:
' <ONE>< TWO>< >< THREE>
'
' 1d) Return all non-whitespace elements with whitespace trimmed:
' The return value contains these 3 elements:
' <ONE><TWO><THREE>
'
' 1e) Split into only two elements:
' The return value contains these 2 elements:
' <><ONE,, TWO,, , THREE,,>
'
' 1f) Split into only two elements with whitespace trimmed:
' The return value contains these 2 elements:
' <><ONE,, TWO,, , THREE,,>
'
' 1g) Split into only two non-empty elements:
' The return value contains these 2 elements:
' <ONE>< TWO,, , THREE,,>
'
' 1h) Split into only two non-whitespace elements with whitespace trimmed:
' The return value contains these 2 elements:
' <ONE><TWO,, , THREE,,>
'
' 2) Split a string delimited by another string:
'
' The original string is: "[stop]ONE[stop] [stop]TWO  [stop][stop]  [stop]THREE[stop][stop]  ".
' The delimiter string is: "[stop]".
'
' 2a) Return all elements:
' The return value contains these 9 elements:
' <><ONE>< ><TWO  ><><  ><THREE><><  >
'
' 2b) Return all elements with whitespace trimmed:
' The return value contains these 9 elements:
' <><ONE><><TWO><><><THREE><><>
'
' 2c) Return all non-empty elements:
' The return value contains these 6 elements:
' <ONE>< ><TWO  ><  ><THREE><  >
'
' 2d) Return all non-whitespace elements with whitespace trimmed:
' The return value contains these 3 elements:
' <ONE><TWO><THREE>
'
' 2e) Split into only two elements:
' The return value contains these 2 elements:
' <><ONE[stop] [stop]TWO  [stop][stop]  [stop]THREE[stop][stop]  >
'
' 2f) Split into only two elements with whitespace trimmed:
' The return value contains these 2 elements:
' <><ONE[stop] [stop]TWO  [stop][stop]  [stop]THREE[stop][stop]>
'
' 2g) Split into only two non-empty elements:
' The return value contains these 2 elements:
' <ONE>< [stop]TWO  [stop][stop]  [stop]THREE[stop][stop]  >
'
' 2h) Split into only two non-whitespace elements with whitespace trimmed:
' The return value contains these 2 elements:
' <ONE><TWO  [stop][stop]  [stop]THREE[stop][stop]>
'

Комментарии

Строки разделителя не включаются в элементы возвращаемого массива.

Если этот экземпляр не содержит ни одной строки в separator, либо count параметр равен 1, возвращаемый массив состоит из одного элемента, содержащего этот экземпляр.

separator Если параметр не содержит null символов, символы пробела считаются разделителями. Символы пробелов определяются стандартом Юникода и Char.IsWhiteSpace метод возвращается true , если они передаются в него.

Чтобы передать null параметр string[] separator , необходимо указать тип null для диамбигации вызова от некоторых других перегрузок, таких как Split(Char[], Int32, StringSplitOptions). В следующем примере показано несколько способов однозначно определить эту перегрузку.

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 Если параметр равен нулю, или optionsRemoveEmptyEntries параметр равен нулю, то возвращается пустой массив.

Каждый элемент определяет отдельный separator разделитель, состоящий из одного или нескольких символов. options Если параметр имеет значение None, а два разделителя находятся рядом или разделитель найден в начале или конце этого экземпляра, соответствующий элемент массива Emptyсодержит.

Если в этом экземпляре имеется больше count подстроок, count первые подстроки минус 1 возвращаются в первых count минус 1 элементов возвращаемого значения, а остальные символы в этом экземпляре возвращаются в последнем элементе возвращаемого значения.

Если count больше числа подстроок, возвращаются доступные подстроки и исключение не возникает.

Массив разделителя

Если любой из элементов состоит separator из нескольких символов, вся подстрока считается разделителем. Например, если один из элементов имеет separator значение "10", пытается разделить строку "This10is10a10string". Возвращает этот четырехэлейный массив: { This, is, "a", "string". }.

Сведения о сравнении

Метод Split извлекает подстроки в этой строке, разделенные одной или несколькими строками в separator параметре, и возвращает эти подстроки в виде элементов массива.

Метод Split ищет разделители, выполняя сравнения с использованием правил порядковой сортировки с учетом регистра. Дополнительные сведения о словах, строках и порядковых сортировках см. в System.Globalization.CompareOptions перечислении.

Метод Split игнорирует любой элемент, значение которого separator имеет значение null или пустую строку ("").

Чтобы избежать неоднозначных результатов при наличии символов separator в строках, Split метод начинается с конца значения экземпляра и соответствует первому элементу, separator равному разделителям в экземпляре. Порядок, в котором встречаются подстроки в экземпляре, имеет приоритет над порядком элементов в separator.

Например, рассмотрим экземпляр, значение которого равно abcdef. Если первый элемент был separator "ef", а второй элемент был "bcde", результат операции разделения будет "a" и "f". Это связано с тем, что подстрока в экземпляре "bcde" встречается и соответствует элементу separator до обнаружения подстроки "f".

Однако если первый элемент separator был "bcd" и второй элемент был "bc", результат операции разделения будет "a" и "ef". Это связано с тем, что bcd является первым разделителем в separator том, что соответствует разделителям в экземпляре. Если порядок разделителей был изменен таким образом, что первый элемент был "bc", а второй элемент был "bcd", результатом будет "a" и "def".

Рекомендации по производительности

Методы Split выделяют память для возвращаемого объекта массива и String объекта для каждого элемента массива. Если приложению требуется оптимальная производительность или если управление выделением памяти критически важно в приложении, рассмотрите возможность использования IndexOf метода или IndexOfAny метода и при необходимости Compare для поиска подстроки в строке.

Если вы разделяете строку в символе разделителя, используйте IndexOf метод или IndexOfAny для поиска символа разделителя в строке. Если вы разделяете строку в строке разделителя, используйте IndexOf или IndexOfAny метод, чтобы найти первый символ строки разделителя. Затем используйте Compare метод, чтобы определить, равны ли символы после этого первого символа оставшимся символам строки разделителя.

Кроме того, если один и тот же набор символов используется для разделения строк в нескольких Split вызовах методов, рассмотрите возможность создания одного массива и ссылки на него в каждом вызове метода. Это значительно снижает дополнительные затраты на каждый вызов метода.

Примечания для тех, кто вызывает этот метод

В .NET Framework 3.5 и более ранних версиях, если Split(Char[]) метод передается или separatornull не содержит символов, метод использует несколько другой набор символов пробела для разделения строки, отличной Trim(Char[]) от метода. Начиная с .NET Framework 4 оба метода используют идентичный набор символов пробелов Юникода.

Применяется к

Split(Rune, Int32, StringSplitOptions)

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

Параметры

separator
Rune
count
Int32

Возвращаемое значение

String[]

Применяется к

Split(Char[], Int32, StringSplitOptions)

Исходный код:
String.Manipulation.cs
Исходный код:
String.Manipulation.cs
Исходный код:
String.Manipulation.cs
Исходный код:
String.Manipulation.cs

Разбивает строку на максимальное количество подстроок на основе указанных символов разделителя и, при необходимости, параметров.

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

Параметры

separator
Char[]

Массив символов, разделяющих подстроки в этой строке, пустой массив, который не содержит разделителей или null.

count
Int32

Максимальное количество возвращаемых подстроок.

options
StringSplitOptions

Побитовое сочетание значений перечисления, указывающее, следует ли обрезать подстроки и включать пустые подстроки.

Возвращаемое значение

String[]

Массив, содержащий подстроки в этой строке, разделенные одним или несколькими символами.separator Дополнительные сведения см. в разделе "Примечания".

Атрибуты

Исключения

count является отрицательным.

options не является одним из значений StringSplitOptions .

Примеры

В следующем примере перечисление StringSplitOptions используется для включения или исключения подстроок, созданных методом Split .

// This example demonstrates the String.Split() methods that use
// the StringSplitOptions enumeration.

// Example 1: Split a string delimited by characters
Console.WriteLine("1) Split a string delimited by characters:\n");

string s1 = ",ONE,, TWO,, , THREE,,";
char[] charSeparators = new char[] { ',' };
string[] result;

Console.WriteLine($"The original string is: \"{s1}\".");
Console.WriteLine($"The delimiter character is: '{charSeparators[0]}'.\n");

// Split the string and return all elements
Console.WriteLine("1a) Return all elements:");
result = s1.Split(charSeparators, StringSplitOptions.None);
Show(result);

// Split the string and return all elements with whitespace trimmed
Console.WriteLine("1b) Return all elements with whitespace trimmed:");
result = s1.Split(charSeparators, StringSplitOptions.TrimEntries);
Show(result);

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

// Split the string and return all non-whitespace elements with whitespace trimmed
Console.WriteLine("1d) Return all non-whitespace elements with whitespace trimmed:");
result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
Show(result);


// Split the string into only two elements, keeping the remainder in the last match
Console.WriteLine("1e) Split into only two elements:");
result = s1.Split(charSeparators, 2, StringSplitOptions.None);
Show(result);

// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("1f) Split into only two elements with whitespace trimmed:");
result = s1.Split(charSeparators, 2, StringSplitOptions.TrimEntries);
Show(result);

// Split the string into only two non-empty elements, keeping the remainder in the last match
Console.WriteLine("1g) Split into only two non-empty elements:");
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries);
Show(result);

// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("1h) Split into only two non-whitespace elements with whitespace trimmed:");
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
Show(result);


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

string s2 = "[stop]" +
            "ONE[stop] [stop]" +
            "TWO  [stop][stop]  [stop]" +
            "THREE[stop][stop]  ";
string[] stringSeparators = new string[] { "[stop]" };

Console.WriteLine($"The original string is: \"{s2}\".");
Console.WriteLine($"The delimiter string is: \"{stringSeparators[0]}\".\n");

// Split the string and return all elements
Console.WriteLine("2a) Return all elements:");
result = s2.Split(stringSeparators, StringSplitOptions.None);
Show(result);

// Split the string and return all elements with whitespace trimmed
Console.WriteLine("2b) Return all elements with whitespace trimmed:");
result = s2.Split(stringSeparators, StringSplitOptions.TrimEntries);
Show(result);

// Split the string and return all non-empty elements
Console.WriteLine("2c) Return all non-empty elements:");
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);
Show(result);

// Split the string and return all non-whitespace elements with whitespace trimmed
Console.WriteLine("2d) Return all non-whitespace elements with whitespace trimmed:");
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
Show(result);


// Split the string into only two elements, keeping the remainder in the last match
Console.WriteLine("2e) Split into only two elements:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.None);
Show(result);

// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("2f) Split into only two elements with whitespace trimmed:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.TrimEntries);
Show(result);

// Split the string into only two non-empty elements, keeping the remainder in the last match
Console.WriteLine("2g) Split into only two non-empty elements:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries);
Show(result);

// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("2h) Split into only two non-whitespace elements with whitespace trimmed:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
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:

The original string is: ",ONE,, TWO,, , THREE,,".
The delimiter character is: ','.

1a) Return all elements:
The return value contains these 9 elements:
<><ONE><>< TWO><>< >< THREE><><>

1b) Return all elements with whitespace trimmed:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>

1c) Return all non-empty elements:
The return value contains these 4 elements:
<ONE>< TWO>< >< THREE>

1d) Return all non-whitespace elements with whitespace trimmed:
The return value contains these 3 elements:
<ONE><TWO><THREE>

1e) Split into only two elements:
The return value contains these 2 elements:
<><ONE,, TWO,, , THREE,,>

1f) Split into only two elements with whitespace trimmed:
The return value contains these 2 elements:
<><ONE,, TWO,, , THREE,,>

1g) Split into only two non-empty elements:
The return value contains these 2 elements:
<ONE>< TWO,, , THREE,,>

1h) Split into only two non-whitespace elements with whitespace trimmed:
The return value contains these 2 elements:
<ONE><TWO,, , THREE,,>

2) Split a string delimited by another string:

The original string is: "[stop]ONE[stop] [stop]TWO  [stop][stop]  [stop]THREE[stop][stop]  ".
The delimiter string is: "[stop]".

2a) Return all elements:
The return value contains these 9 elements:
<><ONE>< ><TWO  ><><  ><THREE><><  >

2b) Return all elements with whitespace trimmed:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>

2c) Return all non-empty elements:
The return value contains these 6 elements:
<ONE>< ><TWO  ><  ><THREE><  >

2d) Return all non-whitespace elements with whitespace trimmed:
The return value contains these 3 elements:
<ONE><TWO><THREE>

2e) Split into only two elements:
The return value contains these 2 elements:
<><ONE[stop] [stop]TWO  [stop][stop]  [stop]THREE[stop][stop]  >

2f) Split into only two elements with whitespace trimmed:
The return value contains these 2 elements:
<><ONE[stop] [stop]TWO  [stop][stop]  [stop]THREE[stop][stop]>

2g) Split into only two non-empty elements:
The return value contains these 2 elements:
<ONE>< [stop]TWO  [stop][stop]  [stop]THREE[stop][stop]  >

2h) Split into only two non-whitespace elements with whitespace trimmed:
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"

// Example 1: Split a string delimited by characters
printfn "1) Split a string delimited by characters:\n"

let s1 = ",ONE,, TWO,, , THREE,,"
let charSeparators = [| ',' |]

printfn $"The original string is: \"{s1}\"."
printfn $"The delimiter character is: '{charSeparators[0]}'.\n"

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

// Split the string and return all elements with whitespace trimmed
printfn "1b) Return all elements with whitespace trimmed:"
let result = s1.Split(charSeparators, StringSplitOptions.TrimEntries)
show result

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

// Split the string and return all non-whitespace elements with whitespace trimmed
printfn "1d) Return all non-whitespace elements with whitespace trimmed:"
let result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)
show result


// Split the string into only two elements, keeping the remainder in the last match
printfn "1e) Split into only two elements:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.None)
show result

// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
printfn "1f) Split into only two elements with whitespace trimmed:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.TrimEntries)
show result

// Split the string into only two non-empty elements, keeping the remainder in the last match
printfn "1g) Split into only two non-empty elements:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
show result

// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
printfn "1h) Split into only two non-whitespace elements with whitespace trimmed:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)
show result


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

let s2 = "[stop]" +
            "ONE[stop] [stop]" +
            "TWO  [stop][stop]  [stop]" +
            "THREE[stop][stop]  "
let stringSeparators = [| "[stop]" |]

printfn $"The original string is: \"{s2}\"."
printfn $"The delimiter string is: \"{stringSeparators[0]}\".\n"

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

// Split the string and return all elements with whitespace trimmed
printfn "2b) Return all elements with whitespace trimmed:"
let result = s2.Split(stringSeparators, StringSplitOptions.TrimEntries)
show result

// Split the string and return all non-empty elements
printfn "2c) Return all non-empty elements:"
let result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)
show result

// Split the string and return all non-whitespace elements with whitespace trimmed
printfn "2d) Return all non-whitespace elements with whitespace trimmed:"
let result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)
show result


// Split the string into only two elements, keeping the remainder in the last match
printfn "2e) Split into only two elements:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.None)
show result

// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
printfn "2f) Split into only two elements with whitespace trimmed:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.TrimEntries)
show result

// Split the string into only two non-empty elements, keeping the remainder in the last match
printfn "2g) Split into only two non-empty elements:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
show result

// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
printfn "2h) Split into only two non-whitespace elements with whitespace trimmed:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)
show result

(*
This example produces the following results:

1) Split a string delimited by characters:

The original string is: ",ONE,, TWO,, , THREE,,".
The delimiter character is: ','.

1a) Return all elements:
The return value contains these 9 elements:
<><ONE><>< TWO><>< >< THREE><><>

1b) Return all elements with whitespace trimmed:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>

1c) Return all non-empty elements:
The return value contains these 4 elements:
<ONE>< TWO>< >< THREE>

1d) Return all non-whitespace elements with whitespace trimmed:
The return value contains these 3 elements:
<ONE><TWO><THREE>

1e) Split into only two elements:
The return value contains these 2 elements:
<><ONE,, TWO,, , THREE,,>

1f) Split into only two elements with whitespace trimmed:
The return value contains these 2 elements:
<><ONE,, TWO,, , THREE,,>

1g) Split into only two non-empty elements:
The return value contains these 2 elements:
<ONE>< TWO,, , THREE,,>

1h) Split into only two non-whitespace elements with whitespace trimmed:
The return value contains these 2 elements:
<ONE><TWO,, , THREE,,>

2) Split a string delimited by another string:

The original string is: "[stop]ONE[stop] [stop]TWO  [stop][stop]  [stop]THREE[stop][stop]  ".
The delimiter string is: "[stop]".

2a) Return all elements:
The return value contains these 9 elements:
<><ONE>< ><TWO  ><><  ><THREE><><  >

2b) Return all elements with whitespace trimmed:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>

2c) Return all non-empty elements:
The return value contains these 6 elements:
<ONE>< ><TWO  ><  ><THREE><  >

2d) Return all non-whitespace elements with whitespace trimmed:
The return value contains these 3 elements:
<ONE><TWO><THREE>

2e) Split into only two elements:
The return value contains these 2 elements:
<><ONE[stop] [stop]TWO  [stop][stop]  [stop]THREE[stop][stop]  >

2f) Split into only two elements with whitespace trimmed:
The return value contains these 2 elements:
<><ONE[stop] [stop]TWO  [stop][stop]  [stop]THREE[stop][stop]>

2g) Split into only two non-empty elements:
The return value contains these 2 elements:
<ONE>< [stop]TWO  [stop][stop]  [stop]THREE[stop][stop]  >

2h) Split into only two non-whitespace elements with whitespace trimmed:
The return value contains these 2 elements:
<ONE><TWO  [stop][stop]  [stop]THREE[stop][stop]>

*)
Public Shared Sub StringSplitOptionsExamples()
    ' This example demonstrates the String.Split() methods that use
    ' the StringSplitOptions enumeration.

    ' Example 1: Split a string delimited by characters
    Console.WriteLine("1) Split a string delimited by characters:" & vbCrLf)

    Dim s1 As String = ",ONE,, TWO,, , THREE,,"
    Dim charSeparators() As Char = {","c}
    Dim result() As String

    Console.WriteLine("The original string is: ""{0}"".", s1)
    Console.WriteLine("The delimiter character is: '{0}'." & vbCrLf, charSeparators(0))

    ' Split the string and return all elements
    Console.WriteLine("1a) Return all elements:")
    result = s1.Split(charSeparators, StringSplitOptions.None)
    Show(result)

    ' Split the string and return all elements with whitespace trimmed
    Console.WriteLine("1b) Return all elements with whitespace trimmed:")
    result = s1.Split(charSeparators, StringSplitOptions.TrimEntries)
    Show(result)

    ' Split the string and return all non-empty elements
    Console.WriteLine("1c) Return all non-empty elements:")
    result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries)
    Show(result)

    ' Split the string and return all non-whitespace elements with whitespace trimmed
    Console.WriteLine("1d) Return all non-whitespace elements with whitespace trimmed:")
    result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries)
    Show(result)


    ' Split the string into only two elements, keeping the remainder in the last match
    Console.WriteLine("1e) Split into only two elements:")
    result = s1.Split(charSeparators, 2, StringSplitOptions.None)
    Show(result)

    ' Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
    Console.WriteLine("1f) Split into only two elements with whitespace trimmed:")
    result = s1.Split(charSeparators, 2, StringSplitOptions.TrimEntries)
    Show(result)

    ' Split the string into only two non-empty elements, keeping the remainder in the last match
    Console.WriteLine("1g) Split into only two non-empty elements:")
    result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
    Show(result)

    ' Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
    Console.WriteLine("1h) Split into only two non-whitespace elements with whitespace trimmed:")
    result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries)
    Show(result)


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

    Dim s2 As String = "[stop]" +
                "ONE[stop] [stop]" +
                "TWO  [stop][stop]  [stop]" +
                "THREE[stop][stop]  "
    Dim stringSeparators() As String = {"[stop]"}


    Console.WriteLine("The original string is: ""{0}"".", s2)
    Console.WriteLine("The delimiter string is: ""{0}""." & vbCrLf, stringSeparators(0))

    ' Split the string and return all elements
    Console.WriteLine("2a) Return all elements:")
    result = s2.Split(stringSeparators, StringSplitOptions.None)
    Show(result)

    ' Split the string and return all elements with whitespace trimmed
    Console.WriteLine("2b) Return all elements with whitespace trimmed:")
    result = s2.Split(stringSeparators, StringSplitOptions.TrimEntries)
    Show(result)

    ' Split the string and return all non-empty elements
    Console.WriteLine("2c) Return all non-empty elements:")
    result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)
    Show(result)

    ' Split the string and return all non-whitespace elements with whitespace trimmed
    Console.WriteLine("2d) Return all non-whitespace elements with whitespace trimmed:")
    result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries)
    Show(result)


    ' Split the string into only two elements, keeping the remainder in the last match
    Console.WriteLine("2e) Split into only two elements:")
    result = s2.Split(stringSeparators, 2, StringSplitOptions.None)
    Show(result)

    ' Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
    Console.WriteLine("2f) Split into only two elements with whitespace trimmed:")
    result = s2.Split(stringSeparators, 2, StringSplitOptions.TrimEntries)
    Show(result)

    ' Split the string into only two non-empty elements, keeping the remainder in the last match
    Console.WriteLine("2g) Split into only two non-empty elements:")
    result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
    Show(result)

    ' Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
    Console.WriteLine("2h) Split into only two non-whitespace elements with whitespace trimmed:")
    result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries)
    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:
'
' The original string is: ",ONE,, TWO,, , THREE,,".
' The delimiter character is: ','.
'
' 1a) Return all elements:
' The return value contains these 9 elements:
' <><ONE><>< TWO><>< >< THREE><><>
'
' 1b) Return all elements with whitespace trimmed:
' The return value contains these 9 elements:
' <><ONE><><TWO><><><THREE><><>
'
' 1c) Return all non-empty elements:
' The return value contains these 4 elements:
' <ONE>< TWO>< >< THREE>
'
' 1d) Return all non-whitespace elements with whitespace trimmed:
' The return value contains these 3 elements:
' <ONE><TWO><THREE>
'
' 1e) Split into only two elements:
' The return value contains these 2 elements:
' <><ONE,, TWO,, , THREE,,>
'
' 1f) Split into only two elements with whitespace trimmed:
' The return value contains these 2 elements:
' <><ONE,, TWO,, , THREE,,>
'
' 1g) Split into only two non-empty elements:
' The return value contains these 2 elements:
' <ONE>< TWO,, , THREE,,>
'
' 1h) Split into only two non-whitespace elements with whitespace trimmed:
' The return value contains these 2 elements:
' <ONE><TWO,, , THREE,,>
'
' 2) Split a string delimited by another string:
'
' The original string is: "[stop]ONE[stop] [stop]TWO  [stop][stop]  [stop]THREE[stop][stop]  ".
' The delimiter string is: "[stop]".
'
' 2a) Return all elements:
' The return value contains these 9 elements:
' <><ONE>< ><TWO  ><><  ><THREE><><  >
'
' 2b) Return all elements with whitespace trimmed:
' The return value contains these 9 elements:
' <><ONE><><TWO><><><THREE><><>
'
' 2c) Return all non-empty elements:
' The return value contains these 6 elements:
' <ONE>< ><TWO  ><  ><THREE><  >
'
' 2d) Return all non-whitespace elements with whitespace trimmed:
' The return value contains these 3 elements:
' <ONE><TWO><THREE>
'
' 2e) Split into only two elements:
' The return value contains these 2 elements:
' <><ONE[stop] [stop]TWO  [stop][stop]  [stop]THREE[stop][stop]  >
'
' 2f) Split into only two elements with whitespace trimmed:
' The return value contains these 2 elements:
' <><ONE[stop] [stop]TWO  [stop][stop]  [stop]THREE[stop][stop]>
'
' 2g) Split into only two non-empty elements:
' The return value contains these 2 elements:
' <ONE>< [stop]TWO  [stop][stop]  [stop]THREE[stop][stop]  >
'
' 2h) Split into only two non-whitespace elements with whitespace trimmed:
' The return value contains these 2 elements:
' <ONE><TWO  [stop][stop]  [stop]THREE[stop][stop]>
'

Комментарии

Символы разделителя не включаются в элементы возвращаемого массива.

Если этот экземпляр не содержит символов или separatorcount параметр равен 1, возвращаемый массив состоит из одного элемента, содержащего этот экземпляр.

separator Если параметр не содержит null символов, символы пробела считаются разделителями. Символы пробелов определяются стандартом Юникода и Char.IsWhiteSpace метод возвращается true , если они передаются в него.

Чтобы передать null параметр char[] separator , необходимо указать тип null для диамбигации вызова от некоторых других перегрузок, таких как Split(String[], Int32, StringSplitOptions). В следующем примере показано несколько способов однозначно определить эту перегрузку.

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 Если параметр равен нулю, или optionsRemoveEmptyEntries параметр равен нулю, то возвращается пустой массив.

Каждый элемент определяет отдельный символ разделителя separator . options Если параметр имеет значение None, а два разделителя находятся рядом или разделитель найден в начале или конце этого экземпляра, соответствующий элемент массива Emptyсодержит.

Если в этом экземпляре имеется больше count подстроок, count первые подстроки минус 1 возвращаются в первых count минус 1 элементов возвращаемого значения, а остальные символы в этом экземпляре возвращаются в последнем элементе возвращаемого значения.

Если count больше числа подстроок, возвращаются доступные подстроки и исключение не возникает.

Рекомендации по производительности

Методы Split выделяют память для возвращаемого объекта массива и String объекта для каждого элемента массива. Если приложению требуется оптимальная производительность или если управление выделением памяти критически важно в приложении, рассмотрите возможность использования IndexOf метода или IndexOfAny метода и при необходимости Compare для поиска подстроки в строке.

Если вы разделяете строку в символе разделителя, используйте IndexOf метод или IndexOfAny для поиска символа разделителя в строке. Если вы разделяете строку в строке разделителя, используйте IndexOf или IndexOfAny метод, чтобы найти первый символ строки разделителя. Затем используйте Compare метод, чтобы определить, равны ли символы после этого первого символа оставшимся символам строки разделителя.

Кроме того, если один и тот же набор символов используется для разделения строк в нескольких Split вызовах методов, рассмотрите возможность создания одного массива и ссылки на него в каждом вызове метода. Это значительно снижает дополнительные затраты на каждый вызов метода.

Примечания для тех, кто вызывает этот метод

В .NET Framework 3.5 и более ранних версиях, если Split(Char[]) метод передается или separatornull не содержит символов, метод использует несколько другой набор символов пробела для разделения строки, отличной Trim(Char[]) от метода. Начиная с .NET Framework 4 оба метода используют идентичный набор символов пробелов Юникода.

Применяется к

Split(Char, Int32, StringSplitOptions)

Исходный код:
String.Manipulation.cs
Исходный код:
String.Manipulation.cs
Исходный код:
String.Manipulation.cs
Исходный код:
String.Manipulation.cs

Разбивает строку на максимальное количество подстроок на основе предоставленного разделителя символов, при необходимости пропуская пустые подстроки из результата.

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

Параметры

separator
Char

Символ, разделяющий подстроки в этом экземпляре.

count
Int32

Максимальное количество элементов, ожидаемых в массиве.

options
StringSplitOptions

Побитовое сочетание значений перечисления, указывающее, следует ли обрезать подстроки и включать пустые подстроки.

Возвращаемое значение

String[]

Массив, содержащий по крайней мере count подстроки из этого экземпляра, разделенный разделителями separator.

Комментарии

Если строка уже разделена count — 1 раз, но конец строки не достигнут, то последняя строка в возвращаемом массиве будет содержать оставшуюся подстроку этого экземпляра без изменений.

Применяется к

Split(String[], StringSplitOptions)

Исходный код:
String.Manipulation.cs
Исходный код:
String.Manipulation.cs
Исходный код:
String.Manipulation.cs
Исходный код:
String.Manipulation.cs

Разбивает строку на подстроки на основе указанной строки разделителя и, при необходимости, параметров.

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

Параметры

separator
String[]

Массив строк, разделяющих подстроки в этой строке, пустой массив, который не содержит разделителей или null.

options
StringSplitOptions

Побитовое сочетание значений перечисления, указывающее, следует ли обрезать подстроки и включать пустые подстроки.

Возвращаемое значение

String[]

Массив, элементы которого содержат подстроки в этой строке, разделенные одной или несколькими строками.separator Дополнительные сведения см. в разделе "Примечания".

Атрибуты

Исключения

options не является одним из значений StringSplitOptions .

Примеры

В следующем примере показано различие в массивах, возвращаемых путем вызова метода строки String.Split(String[], StringSplitOptions) с его options параметром, равным StringSplitOptions.None и 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'

В следующем примере определяется массив разделителей, включающих знаки препинания и пробелы. Передача этого массива вместе со значением StringSplitOptions.RemoveEmptyEntriesSplit(String[], StringSplitOptions) метода возвращает массив, состоящий из отдельных слов из строки.

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

Обратите внимание, что метод вызывается с заданным аргументом optionsStringSplitOptions.RemoveEmptyEntries. Это предотвращает включение String.Empty возвращаемого массива значений, представляющих пустые совпадения подстроки между знаками препинания и символами пробелов.

Комментарии

Если строка разделена известным набором строк, можно использовать Split метод для разделения его на подстроки.

Строки разделителя не включаются в элементы возвращаемого массива. Например, если separator массив содержит строку "--", а значение текущего экземпляра строки — "aa--bb--cc", метод возвращает массив, содержащий три элемента: "aa", "bb" и "cc".

Если этот экземпляр не содержит ни одной строки, separatorвозвращаемый массив состоит из одного элемента, содержащего этот экземпляр.

options Если параметр равен RemoveEmptyEntries нулю, метод возвращает пустой массив.

Каждый элемент определяет отдельный separator разделитель, состоящий из одного или нескольких символов. options Если аргумент имеет значение None, а два разделителя находятся рядом или разделитель найден в начале или конце этого экземпляра, соответствующий элемент массива String.Emptyсодержит. Например, если separator включает два элемента "-" и "_", значение строкового экземпляра равно "-_aa-_", а значение options аргумента — это Noneметод возвращает строковый массив со следующими пятью элементами:

  1. String.Empty, представляющий пустую строку, которая предшествует подстроке "-" по индексу 0.

  2. String.Empty, представляющий пустую строку между подстроками "-" в индексе 0 и подстроками "_" в индексе 1.

  3. "aa".

  4. String.Empty, представляющий пустую строку, которая следует подстроке "-" в индексе 4.

  5. String.Empty, представляющий пустую строку, которая следует подстроке "_" в индексе 5.

Массив разделителя

Если любой из элементов состоит separator из нескольких символов, вся подстрока считается разделителем. Например, если один из элементов в separator строке "10", пытается разделить строку "This10is10a10string". Возвращает следующий массив четырех элементов: { This, is, "a", "string". }.

separator Если параметр не null содержит пустых строк, то символы пробела считаются разделителями. Символы пробелов определяются стандартом Юникода и Char.IsWhiteSpace метод возвращается true , если они передаются в него.

Чтобы передать null параметр string[] separator , необходимо указать тип null для диамбигации вызова от некоторых других перегрузок, таких как Split(Char[], StringSplitOptions). В следующем примере показано несколько способов однозначно определить эту перегрузку.

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)

Сведения о сравнении

Метод Split извлекает подстроки в этой строке, разделенные одной или несколькими строками в separator параметре, и возвращает эти подстроки в виде элементов массива.

Метод Split ищет разделители, выполняя сравнения с использованием правил порядковой сортировки с учетом регистра. Дополнительные сведения о словах, строках и порядковых сортировках см. в System.Globalization.CompareOptions перечислении.

Метод Split игнорирует любой элемент, значение которого separator имеет значение null или пустую строку ("").

Чтобы избежать неоднозначных результатов при наличии символов separator в строках, Split операция выполняется с начала до конца значения экземпляра и соответствует первому элементу, separator который равен разделителям в экземпляре. Порядок, в котором встречаются подстроки в экземпляре, имеет приоритет над порядком элементов в separator.

Например, рассмотрим экземпляр, значение которого равно abcdef. Если первый элемент был separator "ef" и второй элемент был "bcde", результат операции разделения будет строковым массивом, который содержит два элемента: "a" и "f". Это связано с тем, что подстрока в экземпляре "bcde" встречается и соответствует элементу separator до обнаружения подстроки "f".

Однако если первый элемент separator был "bcd", а второй элемент был "bc", результатом операции разделения будет строковый массив, содержащий два элемента: "a" и "ef". Это связано с тем, что bcd является первым разделителем в separator том, что соответствует разделителям в экземпляре. Если порядок разделителей был изменен таким образом, что первый элемент был "bc", а второй элемент был "bcd", результатом будет строковый массив, содержащий два элемента, "a" и "def".

Рекомендации по производительности

Методы Split выделяют память для возвращаемого объекта массива и String объекта для каждого элемента массива. Если приложению требуется оптимальная производительность или если управление выделением памяти критически важно в приложении, рассмотрите возможность использования IndexOf метода или IndexOfAny метода и при необходимости Compare для поиска подстроки в строке.

Если вы разделяете строку в символе разделителя, используйте IndexOf метод или IndexOfAny для поиска символа разделителя в строке. Если вы разделяете строку в строке разделителя, используйте IndexOf или IndexOfAny метод, чтобы найти первый символ строки разделителя. Затем используйте Compare метод, чтобы определить, равны ли символы после этого первого символа оставшимся символам строки разделителя.

Кроме того, если один и тот же набор символов используется для разделения строк в нескольких Split вызовах методов, рассмотрите возможность создания одного массива и ссылки на него в каждом вызове метода. Это значительно снижает дополнительные затраты на каждый вызов метода.

Примечания для тех, кто вызывает этот метод

В .NET Framework 3.5 и более ранних версиях, если Split(Char[]) метод передается или separatornull не содержит символов, метод использует несколько другой набор символов пробела для разделения строки, отличной Trim(Char[]) от метода. Начиная с .NET Framework 4 оба метода используют идентичный набор символов пробелов Юникода.

Применяется к

Split(String, Int32, StringSplitOptions)

Исходный код:
String.Manipulation.cs
Исходный код:
String.Manipulation.cs
Исходный код:
String.Manipulation.cs
Исходный код:
String.Manipulation.cs

Разбивает строку на максимальное количество подстроок на основе указанной строки разделителя и, при необходимости, параметров.

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

Параметры

separator
String

Строка, разделяющая подстроки в этом экземпляре.

count
Int32

Максимальное количество элементов, ожидаемых в массиве.

options
StringSplitOptions

Побитовое сочетание значений перечисления, указывающее, следует ли обрезать подстроки и включать пустые подстроки.

Возвращаемое значение

String[]

Массив, содержащий по крайней мере count подстроки из этого экземпляра, разделенный разделителями separator.

Комментарии

Если строка уже разделена count — 1 раз, но конец строки не достигнут, то последняя строка в возвращаемом массиве будет содержать оставшуюся подстроку этого экземпляра без изменений.

Применяется к

Split(Char[], StringSplitOptions)

Исходный код:
String.Manipulation.cs
Исходный код:
String.Manipulation.cs
Исходный код:
String.Manipulation.cs
Исходный код:
String.Manipulation.cs

Разбивает строку на подстроки на основе указанных символов и параметров разделителя.

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

Параметры

separator
Char[]

Массив символов, разделяющих подстроки в этой строке, пустой массив, который не содержит разделителей или null.

options
StringSplitOptions

Побитовое сочетание значений перечисления, указывающее, следует ли обрезать подстроки и включать пустые подстроки.

Возвращаемое значение

String[]

Массив, элементы которого содержат подстроки в этой строке, разделенные одним или несколькими символами.separator Дополнительные сведения см. в разделе "Примечания".

Атрибуты

Исключения

options не является одним из значений StringSplitOptions .

Примеры

В следующем примере перечисление StringSplitOptions используется для включения или исключения подстроок, созданных методом Split .

// This example demonstrates the String.Split() methods that use
// the StringSplitOptions enumeration.

// Example 1: Split a string delimited by characters
Console.WriteLine("1) Split a string delimited by characters:\n");

string s1 = ",ONE,, TWO,, , THREE,,";
char[] charSeparators = new char[] { ',' };
string[] result;

Console.WriteLine($"The original string is: \"{s1}\".");
Console.WriteLine($"The delimiter character is: '{charSeparators[0]}'.\n");

// Split the string and return all elements
Console.WriteLine("1a) Return all elements:");
result = s1.Split(charSeparators, StringSplitOptions.None);
Show(result);

// Split the string and return all elements with whitespace trimmed
Console.WriteLine("1b) Return all elements with whitespace trimmed:");
result = s1.Split(charSeparators, StringSplitOptions.TrimEntries);
Show(result);

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

// Split the string and return all non-whitespace elements with whitespace trimmed
Console.WriteLine("1d) Return all non-whitespace elements with whitespace trimmed:");
result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
Show(result);


// Split the string into only two elements, keeping the remainder in the last match
Console.WriteLine("1e) Split into only two elements:");
result = s1.Split(charSeparators, 2, StringSplitOptions.None);
Show(result);

// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("1f) Split into only two elements with whitespace trimmed:");
result = s1.Split(charSeparators, 2, StringSplitOptions.TrimEntries);
Show(result);

// Split the string into only two non-empty elements, keeping the remainder in the last match
Console.WriteLine("1g) Split into only two non-empty elements:");
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries);
Show(result);

// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("1h) Split into only two non-whitespace elements with whitespace trimmed:");
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
Show(result);


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

string s2 = "[stop]" +
            "ONE[stop] [stop]" +
            "TWO  [stop][stop]  [stop]" +
            "THREE[stop][stop]  ";
string[] stringSeparators = new string[] { "[stop]" };

Console.WriteLine($"The original string is: \"{s2}\".");
Console.WriteLine($"The delimiter string is: \"{stringSeparators[0]}\".\n");

// Split the string and return all elements
Console.WriteLine("2a) Return all elements:");
result = s2.Split(stringSeparators, StringSplitOptions.None);
Show(result);

// Split the string and return all elements with whitespace trimmed
Console.WriteLine("2b) Return all elements with whitespace trimmed:");
result = s2.Split(stringSeparators, StringSplitOptions.TrimEntries);
Show(result);

// Split the string and return all non-empty elements
Console.WriteLine("2c) Return all non-empty elements:");
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);
Show(result);

// Split the string and return all non-whitespace elements with whitespace trimmed
Console.WriteLine("2d) Return all non-whitespace elements with whitespace trimmed:");
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
Show(result);


// Split the string into only two elements, keeping the remainder in the last match
Console.WriteLine("2e) Split into only two elements:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.None);
Show(result);

// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("2f) Split into only two elements with whitespace trimmed:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.TrimEntries);
Show(result);

// Split the string into only two non-empty elements, keeping the remainder in the last match
Console.WriteLine("2g) Split into only two non-empty elements:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries);
Show(result);

// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("2h) Split into only two non-whitespace elements with whitespace trimmed:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
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:

The original string is: ",ONE,, TWO,, , THREE,,".
The delimiter character is: ','.

1a) Return all elements:
The return value contains these 9 elements:
<><ONE><>< TWO><>< >< THREE><><>

1b) Return all elements with whitespace trimmed:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>

1c) Return all non-empty elements:
The return value contains these 4 elements:
<ONE>< TWO>< >< THREE>

1d) Return all non-whitespace elements with whitespace trimmed:
The return value contains these 3 elements:
<ONE><TWO><THREE>

1e) Split into only two elements:
The return value contains these 2 elements:
<><ONE,, TWO,, , THREE,,>

1f) Split into only two elements with whitespace trimmed:
The return value contains these 2 elements:
<><ONE,, TWO,, , THREE,,>

1g) Split into only two non-empty elements:
The return value contains these 2 elements:
<ONE>< TWO,, , THREE,,>

1h) Split into only two non-whitespace elements with whitespace trimmed:
The return value contains these 2 elements:
<ONE><TWO,, , THREE,,>

2) Split a string delimited by another string:

The original string is: "[stop]ONE[stop] [stop]TWO  [stop][stop]  [stop]THREE[stop][stop]  ".
The delimiter string is: "[stop]".

2a) Return all elements:
The return value contains these 9 elements:
<><ONE>< ><TWO  ><><  ><THREE><><  >

2b) Return all elements with whitespace trimmed:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>

2c) Return all non-empty elements:
The return value contains these 6 elements:
<ONE>< ><TWO  ><  ><THREE><  >

2d) Return all non-whitespace elements with whitespace trimmed:
The return value contains these 3 elements:
<ONE><TWO><THREE>

2e) Split into only two elements:
The return value contains these 2 elements:
<><ONE[stop] [stop]TWO  [stop][stop]  [stop]THREE[stop][stop]  >

2f) Split into only two elements with whitespace trimmed:
The return value contains these 2 elements:
<><ONE[stop] [stop]TWO  [stop][stop]  [stop]THREE[stop][stop]>

2g) Split into only two non-empty elements:
The return value contains these 2 elements:
<ONE>< [stop]TWO  [stop][stop]  [stop]THREE[stop][stop]  >

2h) Split into only two non-whitespace elements with whitespace trimmed:
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"

// Example 1: Split a string delimited by characters
printfn "1) Split a string delimited by characters:\n"

let s1 = ",ONE,, TWO,, , THREE,,"
let charSeparators = [| ',' |]

printfn $"The original string is: \"{s1}\"."
printfn $"The delimiter character is: '{charSeparators[0]}'.\n"

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

// Split the string and return all elements with whitespace trimmed
printfn "1b) Return all elements with whitespace trimmed:"
let result = s1.Split(charSeparators, StringSplitOptions.TrimEntries)
show result

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

// Split the string and return all non-whitespace elements with whitespace trimmed
printfn "1d) Return all non-whitespace elements with whitespace trimmed:"
let result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)
show result


// Split the string into only two elements, keeping the remainder in the last match
printfn "1e) Split into only two elements:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.None)
show result

// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
printfn "1f) Split into only two elements with whitespace trimmed:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.TrimEntries)
show result

// Split the string into only two non-empty elements, keeping the remainder in the last match
printfn "1g) Split into only two non-empty elements:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
show result

// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
printfn "1h) Split into only two non-whitespace elements with whitespace trimmed:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)
show result


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

let s2 = "[stop]" +
            "ONE[stop] [stop]" +
            "TWO  [stop][stop]  [stop]" +
            "THREE[stop][stop]  "
let stringSeparators = [| "[stop]" |]

printfn $"The original string is: \"{s2}\"."
printfn $"The delimiter string is: \"{stringSeparators[0]}\".\n"

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

// Split the string and return all elements with whitespace trimmed
printfn "2b) Return all elements with whitespace trimmed:"
let result = s2.Split(stringSeparators, StringSplitOptions.TrimEntries)
show result

// Split the string and return all non-empty elements
printfn "2c) Return all non-empty elements:"
let result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)
show result

// Split the string and return all non-whitespace elements with whitespace trimmed
printfn "2d) Return all non-whitespace elements with whitespace trimmed:"
let result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)
show result


// Split the string into only two elements, keeping the remainder in the last match
printfn "2e) Split into only two elements:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.None)
show result

// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
printfn "2f) Split into only two elements with whitespace trimmed:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.TrimEntries)
show result

// Split the string into only two non-empty elements, keeping the remainder in the last match
printfn "2g) Split into only two non-empty elements:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
show result

// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
printfn "2h) Split into only two non-whitespace elements with whitespace trimmed:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)
show result

(*
This example produces the following results:

1) Split a string delimited by characters:

The original string is: ",ONE,, TWO,, , THREE,,".
The delimiter character is: ','.

1a) Return all elements:
The return value contains these 9 elements:
<><ONE><>< TWO><>< >< THREE><><>

1b) Return all elements with whitespace trimmed:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>

1c) Return all non-empty elements:
The return value contains these 4 elements:
<ONE>< TWO>< >< THREE>

1d) Return all non-whitespace elements with whitespace trimmed:
The return value contains these 3 elements:
<ONE><TWO><THREE>

1e) Split into only two elements:
The return value contains these 2 elements:
<><ONE,, TWO,, , THREE,,>

1f) Split into only two elements with whitespace trimmed:
The return value contains these 2 elements:
<><ONE,, TWO,, , THREE,,>

1g) Split into only two non-empty elements:
The return value contains these 2 elements:
<ONE>< TWO,, , THREE,,>

1h) Split into only two non-whitespace elements with whitespace trimmed:
The return value contains these 2 elements:
<ONE><TWO,, , THREE,,>

2) Split a string delimited by another string:

The original string is: "[stop]ONE[stop] [stop]TWO  [stop][stop]  [stop]THREE[stop][stop]  ".
The delimiter string is: "[stop]".

2a) Return all elements:
The return value contains these 9 elements:
<><ONE>< ><TWO  ><><  ><THREE><><  >

2b) Return all elements with whitespace trimmed:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>

2c) Return all non-empty elements:
The return value contains these 6 elements:
<ONE>< ><TWO  ><  ><THREE><  >

2d) Return all non-whitespace elements with whitespace trimmed:
The return value contains these 3 elements:
<ONE><TWO><THREE>

2e) Split into only two elements:
The return value contains these 2 elements:
<><ONE[stop] [stop]TWO  [stop][stop]  [stop]THREE[stop][stop]  >

2f) Split into only two elements with whitespace trimmed:
The return value contains these 2 elements:
<><ONE[stop] [stop]TWO  [stop][stop]  [stop]THREE[stop][stop]>

2g) Split into only two non-empty elements:
The return value contains these 2 elements:
<ONE>< [stop]TWO  [stop][stop]  [stop]THREE[stop][stop]  >

2h) Split into only two non-whitespace elements with whitespace trimmed:
The return value contains these 2 elements:
<ONE><TWO  [stop][stop]  [stop]THREE[stop][stop]>

*)
Public Shared Sub StringSplitOptionsExamples()
    ' This example demonstrates the String.Split() methods that use
    ' the StringSplitOptions enumeration.

    ' Example 1: Split a string delimited by characters
    Console.WriteLine("1) Split a string delimited by characters:" & vbCrLf)

    Dim s1 As String = ",ONE,, TWO,, , THREE,,"
    Dim charSeparators() As Char = {","c}
    Dim result() As String

    Console.WriteLine("The original string is: ""{0}"".", s1)
    Console.WriteLine("The delimiter character is: '{0}'." & vbCrLf, charSeparators(0))

    ' Split the string and return all elements
    Console.WriteLine("1a) Return all elements:")
    result = s1.Split(charSeparators, StringSplitOptions.None)
    Show(result)

    ' Split the string and return all elements with whitespace trimmed
    Console.WriteLine("1b) Return all elements with whitespace trimmed:")
    result = s1.Split(charSeparators, StringSplitOptions.TrimEntries)
    Show(result)

    ' Split the string and return all non-empty elements
    Console.WriteLine("1c) Return all non-empty elements:")
    result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries)
    Show(result)

    ' Split the string and return all non-whitespace elements with whitespace trimmed
    Console.WriteLine("1d) Return all non-whitespace elements with whitespace trimmed:")
    result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries)
    Show(result)


    ' Split the string into only two elements, keeping the remainder in the last match
    Console.WriteLine("1e) Split into only two elements:")
    result = s1.Split(charSeparators, 2, StringSplitOptions.None)
    Show(result)

    ' Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
    Console.WriteLine("1f) Split into only two elements with whitespace trimmed:")
    result = s1.Split(charSeparators, 2, StringSplitOptions.TrimEntries)
    Show(result)

    ' Split the string into only two non-empty elements, keeping the remainder in the last match
    Console.WriteLine("1g) Split into only two non-empty elements:")
    result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
    Show(result)

    ' Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
    Console.WriteLine("1h) Split into only two non-whitespace elements with whitespace trimmed:")
    result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries)
    Show(result)


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

    Dim s2 As String = "[stop]" +
                "ONE[stop] [stop]" +
                "TWO  [stop][stop]  [stop]" +
                "THREE[stop][stop]  "
    Dim stringSeparators() As String = {"[stop]"}


    Console.WriteLine("The original string is: ""{0}"".", s2)
    Console.WriteLine("The delimiter string is: ""{0}""." & vbCrLf, stringSeparators(0))

    ' Split the string and return all elements
    Console.WriteLine("2a) Return all elements:")
    result = s2.Split(stringSeparators, StringSplitOptions.None)
    Show(result)

    ' Split the string and return all elements with whitespace trimmed
    Console.WriteLine("2b) Return all elements with whitespace trimmed:")
    result = s2.Split(stringSeparators, StringSplitOptions.TrimEntries)
    Show(result)

    ' Split the string and return all non-empty elements
    Console.WriteLine("2c) Return all non-empty elements:")
    result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)
    Show(result)

    ' Split the string and return all non-whitespace elements with whitespace trimmed
    Console.WriteLine("2d) Return all non-whitespace elements with whitespace trimmed:")
    result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries)
    Show(result)


    ' Split the string into only two elements, keeping the remainder in the last match
    Console.WriteLine("2e) Split into only two elements:")
    result = s2.Split(stringSeparators, 2, StringSplitOptions.None)
    Show(result)

    ' Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
    Console.WriteLine("2f) Split into only two elements with whitespace trimmed:")
    result = s2.Split(stringSeparators, 2, StringSplitOptions.TrimEntries)
    Show(result)

    ' Split the string into only two non-empty elements, keeping the remainder in the last match
    Console.WriteLine("2g) Split into only two non-empty elements:")
    result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
    Show(result)

    ' Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
    Console.WriteLine("2h) Split into only two non-whitespace elements with whitespace trimmed:")
    result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries)
    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:
'
' The original string is: ",ONE,, TWO,, , THREE,,".
' The delimiter character is: ','.
'
' 1a) Return all elements:
' The return value contains these 9 elements:
' <><ONE><>< TWO><>< >< THREE><><>
'
' 1b) Return all elements with whitespace trimmed:
' The return value contains these 9 elements:
' <><ONE><><TWO><><><THREE><><>
'
' 1c) Return all non-empty elements:
' The return value contains these 4 elements:
' <ONE>< TWO>< >< THREE>
'
' 1d) Return all non-whitespace elements with whitespace trimmed:
' The return value contains these 3 elements:
' <ONE><TWO><THREE>
'
' 1e) Split into only two elements:
' The return value contains these 2 elements:
' <><ONE,, TWO,, , THREE,,>
'
' 1f) Split into only two elements with whitespace trimmed:
' The return value contains these 2 elements:
' <><ONE,, TWO,, , THREE,,>
'
' 1g) Split into only two non-empty elements:
' The return value contains these 2 elements:
' <ONE>< TWO,, , THREE,,>
'
' 1h) Split into only two non-whitespace elements with whitespace trimmed:
' The return value contains these 2 elements:
' <ONE><TWO,, , THREE,,>
'
' 2) Split a string delimited by another string:
'
' The original string is: "[stop]ONE[stop] [stop]TWO  [stop][stop]  [stop]THREE[stop][stop]  ".
' The delimiter string is: "[stop]".
'
' 2a) Return all elements:
' The return value contains these 9 elements:
' <><ONE>< ><TWO  ><><  ><THREE><><  >
'
' 2b) Return all elements with whitespace trimmed:
' The return value contains these 9 elements:
' <><ONE><><TWO><><><THREE><><>
'
' 2c) Return all non-empty elements:
' The return value contains these 6 elements:
' <ONE>< ><TWO  ><  ><THREE><  >
'
' 2d) Return all non-whitespace elements with whitespace trimmed:
' The return value contains these 3 elements:
' <ONE><TWO><THREE>
'
' 2e) Split into only two elements:
' The return value contains these 2 elements:
' <><ONE[stop] [stop]TWO  [stop][stop]  [stop]THREE[stop][stop]  >
'
' 2f) Split into only two elements with whitespace trimmed:
' The return value contains these 2 elements:
' <><ONE[stop] [stop]TWO  [stop][stop]  [stop]THREE[stop][stop]>
'
' 2g) Split into only two non-empty elements:
' The return value contains these 2 elements:
' <ONE>< [stop]TWO  [stop][stop]  [stop]THREE[stop][stop]  >
'
' 2h) Split into only two non-whitespace elements with whitespace trimmed:
' The return value contains these 2 elements:
' <ONE><TWO  [stop][stop]  [stop]THREE[stop][stop]>
'

Комментарии

Символы разделителя (символы в массиве separator ) не включаются в элементы возвращаемого массива. Например, если separator массив содержит символ -" и значение текущего экземпляра строки "aa-bb-cc", метод возвращает массив, содержащий три элемента: "aa", "bb" и "cc".

Если этот экземпляр не содержит символов в separator, возвращаемый массив состоит из одного элемента, содержащего этот экземпляр.

options Если параметр равен RemoveEmptyEntries нулю, метод возвращает пустой массив.

Каждый элемент separator определяет отдельный разделитель, состоящий из одного символа. options Если аргумент имеет значение None, а два разделителя находятся рядом или разделитель найден в начале или конце этого экземпляра, соответствующий элемент массива String.Emptyсодержит. Например, если separator содержит два элемента, '-' а '_'значение строкового экземпляра — "-_aa-_", а значение options аргумента — это Noneметод возвращает строковый массив со следующими пятью элементами:

  1. String.Empty, представляющий пустую строку, которая предшествует символу "-" в индексе 0.

  2. String.Empty, представляющий пустую строку между символом "-" в индексе 0 и символом "_" в индексе 1.

  3. "aa".

  4. String.Empty, представляющий пустую строку, которая следует символу "-" в индексе 4.

  5. String.Empty, представляющий пустую строку, которая следует символу "_" в индексе 5.

Массив разделителя

separator Если параметр не содержит null символов, символы пробела считаются разделителями. Символы пробелов определяются стандартом Юникода и Char.IsWhiteSpace метод возвращается true , если они передаются в него.

Чтобы передать null параметр char[] separator , необходимо указать тип null для диамбигации вызова от некоторых других перегрузок, таких как Split(String[], StringSplitOptions). В следующем примере показано несколько способов однозначно определить эту перегрузку.

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)

Сведения о сравнении

Метод Split извлекает подстроки в этой строке, разделенные одним или несколькими символами в separator параметре, и возвращает эти подстроки в виде элементов массива.

Метод Split ищет разделители, выполняя сравнения с использованием правил порядковой сортировки с учетом регистра. Дополнительные сведения о словах, строках и порядковых сортировках см. в System.Globalization.CompareOptions перечислении.

Рекомендации по производительности

Методы Split выделяют память для возвращаемого объекта массива и String объекта для каждого элемента массива. Если приложению требуется оптимальная производительность или если управление выделением памяти критически важно в приложении, рассмотрите возможность использования IndexOf метода или IndexOfAny метода и при необходимости Compare для поиска подстроки в строке.

Если вы разделяете строку в символе разделителя, используйте IndexOf метод или IndexOfAny для поиска символа разделителя в строке. Если вы разделяете строку в строке разделителя, используйте IndexOf или IndexOfAny метод, чтобы найти первый символ строки разделителя. Затем используйте Compare метод, чтобы определить, равны ли символы после этого первого символа оставшимся символам строки разделителя.

Кроме того, если один и тот же набор символов используется для разделения строк в нескольких Split вызовах методов, рассмотрите возможность создания одного массива и ссылки на него в каждом вызове метода. Это значительно снижает дополнительные затраты на каждый вызов метода.

Примечания для тех, кто вызывает этот метод

В .NET Framework 3.5 и более ранних версиях, если Split(Char[]) метод передается или separatornull не содержит символов, метод использует несколько другой набор символов пробела для разделения строки, отличной Trim(Char[]) от метода. Начиная с .NET Framework 4 оба метода используют идентичный набор символов пробелов Юникода.

Применяется к

Split(Char[], Int32)

Исходный код:
String.Manipulation.cs
Исходный код:
String.Manipulation.cs
Исходный код:
String.Manipulation.cs
Исходный код:
String.Manipulation.cs

Разбивает строку на максимальное количество подстроок на основе указанных символов разделителей.

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

Параметры

separator
Char[]

Массив символов, разделяющих подстроки в этой строке, пустой массив, который не содержит разделителей или null.

count
Int32

Максимальное количество возвращаемых подстроок.

Возвращаемое значение

String[]

Массив, элементы которого содержат подстроки в этом экземпляре, разделенные одним или несколькими символами.separator Дополнительные сведения см. в разделе "Примечания".

Исключения

count является отрицательным.

Примеры

В следующем примере показано, как count можно использовать для ограничения количества строк, возвращаемых Split.

string name = "Alex Johnson III";

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

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

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

let subs = name.Split(null, 2)

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

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

Dim substrings = name.Split(" "c, count:=2)
Dim firstName As String = substrings(0)
Dim lastName As String

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

Console.WriteLine("firstName = ""{0}""", firstName)
Console.WriteLine("lastName = ""{0}""", lastName)

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

Комментарии

Символы разделителя не включаются в элементы возвращаемого массива.

Если этот экземпляр не содержит символов в separator, возвращаемый массив состоит из одного элемента, содержащего этот экземпляр. Если count значение равно нулю, возвращается пустой массив.

separator Если параметр не содержит null символов, символы пробела считаются разделителями. Символы пробелов определяются стандартом Юникода и Char.IsWhiteSpace метод возвращается true , если они передаются в него.

Каждый элемент определяет отдельный символ разделителя separator . Если два разделителя находятся рядом, или разделитель найден в начале или конце этого экземпляра, соответствующий элемент массива Emptyсодержится.

Если в этом экземпляре больше count подстроок, первые count - 1 подстроки возвращаются в первых count - 1 элементах возвращаемого значения, а остальные символы в этом экземпляре возвращаются в последнем элементе возвращаемого значения.

Если count больше числа подстроок, возвращаются доступные подстроки и исключение не возникает.

В следующей таблице показаны некоторые примеры.

Язык Строковое значение Разделитель Возвращенный массив
C# "42, 12, 19" new Char[] {',', ' '} {"42", "", "12", "", "19"}
Visual Basic "42, 12, 19" Char() = {","c", "c}) {"42", "", "12", "", "19"}
C# "42..12..19." new Char[] {'''} {"42", "", "12", "", "19", ""}
Visual Basic "42..12..19." Char() = {". c} {"42", "", "12", "", "19", ""}
C# "Банан" new Char[] {'''} {"Банан"}
Visual Basic "Банан" Char() = {". c} {"Банан"}
C# "Дарб\nСмарба" new Char[] {} {"Darb", "Smarba"}
Visual Basic "Darb" & vbLf & "Smarba" Char() = {} {"Darb", "Smarba"}
C# "Дарб\nСмарба" недействительный {"Darb", "Smarba"}
Visual Basic "Darb" & vbLf & "Smarba" Ничто {"Darb", "Smarba"}

Рекомендации по производительности

Методы Split выделяют память для возвращаемого объекта массива и String объекта для каждого элемента массива. Если приложению требуется оптимальная производительность или если управление выделением памяти критически важно в приложении, рассмотрите возможность использования IndexOf метода или IndexOfAny метода и при необходимости Compare для поиска подстроки в строке.

Если вы разделяете строку в символе разделителя, используйте IndexOf метод или IndexOfAny для поиска символа разделителя в строке. Если вы разделяете строку в строке разделителя, используйте IndexOf или IndexOfAny метод, чтобы найти первый символ строки разделителя. Затем используйте Compare метод, чтобы определить, равны ли символы после этого первого символа оставшимся символам строки разделителя.

Кроме того, если один и тот же набор символов используется для разделения строк в нескольких Split вызовах методов, рассмотрите возможность создания одного массива и ссылки на него в каждом вызове метода. Это значительно снижает дополнительные затраты на каждый вызов метода.

Примечания для тех, кто вызывает этот метод

В .NET Framework 3.5 и более ранних версиях, если Split(Char[]) метод передается или separatornull не содержит символов, метод использует несколько другой набор символов пробела для разделения строки, отличной Trim(Char[]) от метода. Начиная с .NET Framework 4 оба метода используют идентичный набор символов пробелов Юникода.

См. также раздел

Применяется к

Split(Char, StringSplitOptions)

Исходный код:
String.Manipulation.cs
Исходный код:
String.Manipulation.cs
Исходный код:
String.Manipulation.cs
Исходный код:
String.Manipulation.cs

Разбивает строку на подстроки на основе указанного символа разделителя и, при необходимости, параметров.

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

Параметры

separator
Char

Символ, разделяющий подстроки в этой строке.

options
StringSplitOptions

Побитовое сочетание значений перечисления, указывающее, следует ли обрезать подстроки и включать пустые подстроки.

Возвращаемое значение

String[]

Массив, элементы которого содержат подстроки из этого экземпляра, разделенные разделителями separator.

Применяется к

Split(ReadOnlySpan<Char>)

Исходный код:
String.Manipulation.cs

Разбивает строку на подстроки на основе указанных символов разделителей.

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

Параметры

separator
ReadOnlySpan<Char>

Диапазон символов с разделителями или пустой диапазон, который не содержит разделителей.

Возвращаемое значение

String[]

Массив, элементы которого содержат подстроки из этого экземпляра, разделенные одним или несколькими символами.separator

Применяется к

Split(Char[])

Исходный код:
String.Manipulation.cs
Исходный код:
String.Manipulation.cs
Исходный код:
String.Manipulation.cs
Исходный код:
String.Manipulation.cs

Разбивает строку на подстроки на основе указанных символов разделителей.

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

Параметры

separator
Char[]

Массив символов с разделителями, пустой массив, который не содержит разделителей или null.

Возвращаемое значение

String[]

Массив, элементы которого содержат подстроки из этого экземпляра, разделенные одним или несколькими символами.separator Дополнительные сведения см. в разделе "Примечания".

Примеры

В следующем примере показано, как извлечь отдельные слова из блока текста, обрабатывая символ пробела ( ) и символ табуляции (\t) как разделители. Разделенная строка включает оба этих символа.

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

Комментарии

Если строка разделена известным набором символов, можно использовать Split(Char[]) метод для разделения его на подстроки.

Символы разделителя не включаются в элементы возвращаемого массива. Например, если массив разделителя содержит символ "-" и значение текущего экземпляра строки имеет значение "aa-bb-cc", метод возвращает массив, содержащий три элемента: "aa", "bb" и "cc".

Если этот экземпляр не содержит символов в separator, возвращаемый массив состоит из одного элемента, содержащего этот экземпляр.

Каждый элемент определяет отдельный символ разделителя separator . Если два разделителя находятся рядом, или разделитель найден в начале или конце этого экземпляра, соответствующий элемент в возвращаемом массиве Emptyсодержится.

В следующей таблице показаны некоторые примеры.

Язык Строковое значение Разделитель Возвращенный массив
C# "42, 12, 19" new Char[] {',', ' '} {"42", "", "12", "", "19"}
Visual Basic "42, 12, 19" Char() = {","c", "c}) {"42", "", "12", "", "19"}
C# "42..12..19." new Char[] {'''} {"42", "", "12", "", "19", ""}
Visual Basic "42..12..19." Char() = {". c} {"42", "", "12", "", "19", ""}
C# "Банан" new Char[] {'''} {"Банан"}
Visual Basic "Банан" Char() = {". c} {"Банан"}
C# "Дарб\nСмарба" new Char[] {} {"Darb", "Smarba"}
Visual Basic "Darb" & vbLf & "Smarba" Char() = {} {"Darb", "Smarba"}
C# "Дарб\nСмарба" недействительный {"Darb", "Smarba"}
Visual Basic "Darb" & vbLf & "Smarba" Ничто {"Darb", "Smarba"}

Массив разделителя

Каждый элемент разделителя определяет отдельный разделитель, состоящий из одного символа.

separator Если аргумент не содержит null символов, метод обрабатывает символы пробелов как разделители. Символы пробелов определяются стандартом Юникода, а Char.IsWhiteSpace метод возвращается true , если в него передается символ пробела.

String.Split(Char[]) и разрешение перегрузки компилятора

Хотя один параметр для этой перегрузки является массивом символов String.Split , его можно вызвать одним символом, как показано в следующем примере.

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 Так как параметр украшен ParamArrayAttribute атрибутом, компиляторы интерпретируют один символ в виде массива символов с одним элементом. Это не относится к другим String.Split перегрузкам, которые включают separator параметр. Эти перегрузки необходимо явно передать массив символов в качестве аргумента separator .

Сведения о сравнении

Метод Split(Char[]) извлекает подстроки в этой строке, разделенные одним или несколькими символами в separator массиве, и возвращает эти подстроки в виде элементов массива.

Метод Split(Char[]) ищет разделители, выполняя сравнения с использованием правил порядковой сортировки с учетом регистра. Дополнительные сведения о словах, строках и порядковых сортировках см. в System.Globalization.CompareOptions перечислении.

Рекомендации по производительности

Методы Split выделяют память для возвращаемого объекта массива и String объекта для каждого элемента массива. Если приложению требуется оптимальная производительность или если управление выделением памяти критически важно в приложении, рассмотрите возможность использования IndexOf или IndexOfAny метода. Вы также можете использовать Compare метод для поиска подстроки в строке.

Чтобы разделить строку по символу разделителя, используйте IndexOf метод или IndexOfAny для поиска символа разделителя в строке. Чтобы разделить строку в строке разделителя, используйте IndexOf или IndexOfAny метод, чтобы найти первый символ строки разделителя. Затем используйте Compare метод, чтобы определить, равны ли символы после этого первого символа оставшимся символам строки разделителя.

Кроме того, если один и тот же набор символов используется для разделения строк в нескольких Split вызовах методов, рассмотрите возможность создания одного массива и ссылки на него в каждом вызове метода. Это значительно снижает дополнительные затраты на каждый вызов метода.

Примечания для тех, кто вызывает этот метод

В .NET Framework 3.5 и более ранних версиях, если Split(Char[]) метод передается или separatornull не содержит символов, метод использует несколько другой набор символов пробела для разделения строки, отличной Trim(Char[]) от метода. Начиная с .NET Framework 4 оба метода используют идентичный набор символов пробелов Юникода.

См. также раздел

Применяется к

Split(String, StringSplitOptions)

Исходный код:
String.Manipulation.cs
Исходный код:
String.Manipulation.cs
Исходный код:
String.Manipulation.cs
Исходный код:
String.Manipulation.cs

Разбивает строку на подстроки, основанные на предоставленном разделитетеле строк.

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

Параметры

separator
String

Строка, разделяющая подстроки в этой строке.

options
StringSplitOptions

Побитовое сочетание значений перечисления, указывающее, следует ли обрезать подстроки и включать пустые подстроки.

Возвращаемое значение

String[]

Массив, элементы которого содержат подстроки из этого экземпляра, разделенные разделителями separator.

Применяется к