通过


String.Split 方法

定义

返回一个字符串数组,该数组包含此实例中的子字符串,这些子字符串由指定字符串或 Unicode 字符数组的元素分隔。

重载

名称 说明
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(Char[], Int32))返回的Split子字符串数,以指定是在结果Split(Char[], StringSplitOptions)(和方法)中包括空字符串和/或剪裁子字符串,还是同时执行(Split(Char[], Int32, StringSplitOptions)Split(String[], 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)

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
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]>
'

注解

分隔符字符串不包括在返回数组的元素中。

如果此实例不包含任何字符串, separatorcount 参数为 1,则返回的数组由包含此实例的单个元素组成。

separator如果参数不null包含任何字符,则假定空格字符为分隔符。 空格字符由 Unicode 标准定义,如果 Char.IsWhiteSpace 方法传递给该字符,则返回 true 这些字符。

若要为参数传递null,必须指示要消除其他重载(例如Split(Char[], Int32, StringSplitOptions))的调用的歧义的类型nullstring[] separator 以下示例演示了几种明确标识此重载的方法。

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如果参数为零,或options参数为RemoveEmptyEntries零且此实例的长度为零,则返回空数组。

每个元素 separator 定义由一个或多个字符组成的单独分隔符。 options如果参数是None,并且两个分隔符是相邻的,或者在此实例的开头或末尾找到一个分隔符,则相应的数组元素包含Empty

如果此实例中有多个 count 子字符串,则 count 返回值的第一个减 1 个子字符串在第一 count 个减 1 个元素中返回,此实例中的剩余字符在返回值的最后一个元素中返回。

如果 count 大于子字符串的数目,则返回可用的子字符串,并且不会引发异常。

分隔符数组

如果其中 separator 任一元素由多个字符组成,则整个子字符串被视为分隔符。 例如,如果其中一个元素 separator 为“10”,则尝试拆分字符串“This10is10a10string”。

比较详细信息

该方法 Split 提取此字符串中的子字符串,这些子字符串由参数中的 separator 一个或多个字符串分隔,并将这些子字符串作为数组的元素返回。

该方法 Split 通过使用区分大小写的序号排序规则执行比较来查找分隔符。 有关单词、字符串和序号排序的详细信息,请参阅 System.Globalization.CompareOptions 枚举。

该方法Split忽略其值为null或空字符串(“)的任何元素separator

为避免当字符串 separator 具有常见字符时出现不明确的结果,该方法 Split 从实例值的开头到末尾继续,并将该元素中的 separator 第一个元素与实例中的分隔符匹配。 实例中遇到子字符串的顺序优先于元素的顺序 separator

例如,请考虑其值为“abcdef”的实例。 如果第一个元素是“ef”,第二个元素 separator 是“bcde”,则拆分作的结果将是“a”和“f”。 这是因为遇到实例“bcde”中的子字符串,并在遇到子字符串“f”之前匹配元素 separator

但是,如果第一个元素是“bcd”,第二个元素 separator 是“bc”,则拆分作的结果将是“a”和“ef”。 这是因为“bcd”是第一个与实例中的分隔符匹配的分隔符 separator 。 如果分隔符的顺序被反转,因此第一个元素为“bc”,第二个元素为“bcd”,则结果为“a”和“def”。

性能注意事项

这些 Split 方法为返回的数组对象分配内存,并为每个数组元素分配一个 String 对象。 如果应用程序需要最佳性能,或者如果管理内存分配在应用程序中至关重要,请考虑使用 IndexOfIndexOfAny 方法(可选 Compare )在字符串中查找子字符串。

如果要在分隔符处拆分字符串,请使用 IndexOfIndexOfAny 方法在字符串中找到分隔符。 如果要在分隔符字符串中拆分字符串,请使用 IndexOfIndexOfAny 方法查找分隔符字符串的第一个字符。 然后,使用 Compare 该方法确定第一个字符之后的字符是否等于分隔符字符串的剩余字符。

此外,如果使用同一组字符在多个 Split 方法调用中拆分字符串,请考虑在每个方法调用中创建一个数组并引用它。 这大大减少了每个方法调用的额外开销。

调用方说明

在 .NET Framework 3.5 和更早版本中,如果Split(Char[])方法传递separatornull的是或不包含任何字符,则该方法使用略有不同的空格字符集来拆分字符串,而不是Trim(Char[])该方法剪裁字符串。 从 .NET Framework 4 开始,这两种方法都使用相同的 Unicode 空格字符集。

适用于

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)

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
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]>
'

注解

返回数组的元素中不包含分隔符字符。

如果此实例不包含任何字符 separator,或 count 参数为 1,则返回的数组由包含此实例的单个元素组成。

separator如果参数不null包含任何字符,则假定空格字符为分隔符。 空格字符由 Unicode 标准定义,如果 Char.IsWhiteSpace 方法传递给该字符,则返回 true 这些字符。

若要为参数传递null,必须指示要消除其他重载(例如Split(String[], Int32, StringSplitOptions))的调用的歧义的类型nullchar[] separator 以下示例演示了几种明确标识此重载的方法。

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如果参数为零,或options参数为RemoveEmptyEntries零且此实例的长度为零,则返回空数组。

每个元素 separator 定义单独的分隔符字符。 options如果参数是None,并且两个分隔符是相邻的,或者在此实例的开头或末尾找到一个分隔符,则相应的数组元素包含Empty

如果此实例中有多个 count 子字符串,则 count 返回值的第一个减 1 个子字符串在第一 count 个减 1 个元素中返回,此实例中的剩余字符在返回值的最后一个元素中返回。

如果 count 大于子字符串的数目,则返回可用的子字符串,并且不会引发异常。

性能注意事项

这些 Split 方法为返回的数组对象分配内存,并为每个数组元素分配一个 String 对象。 如果应用程序需要最佳性能,或者如果管理内存分配在应用程序中至关重要,请考虑使用 IndexOfIndexOfAny 方法(可选 Compare )在字符串中查找子字符串。

如果要在分隔符处拆分字符串,请使用 IndexOfIndexOfAny 方法在字符串中找到分隔符。 如果要在分隔符字符串中拆分字符串,请使用 IndexOfIndexOfAny 方法查找分隔符字符串的第一个字符。 然后,使用 Compare 该方法确定第一个字符之后的字符是否等于分隔符字符串的剩余字符。

此外,如果使用同一组字符在多个 Split 方法调用中拆分字符串,请考虑在每个方法调用中创建一个数组并引用它。 这大大减少了每个方法调用的额外开销。

调用方说明

在 .NET Framework 3.5 和更早版本中,如果Split(Char[])方法传递separatornull的是或不包含任何字符,则该方法使用略有不同的空格字符集来拆分字符串,而不是Trim(Char[])该方法剪裁字符串。 从 .NET Framework 4 开始,这两种方法都使用相同的 Unicode 空格字符集。

适用于

Split(Char, Int32, StringSplitOptions)

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
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[]

一个数组,该数组包含此实例中由该实例分隔的separator最多count子字符串。

注解

如果字符串已被拆分 count - 1 次,但尚未到达字符串的末尾,则返回的数组中的最后一个字符串将包含此实例的剩余尾随子字符串(未更改)。

适用于

Split(String[], StringSplitOptions)

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
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 之一。

示例

下面的示例演示了通过调用字符串方法(其options参数等于StringSplitOptions.NoneStringSplitOptions.RemoveEmptyEntries)返回的String.Split(String[], StringSplitOptions)数组之间的差异。

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

请注意,该方法在参数设置为 <a0/> 的情况下调用。 这可以防止返回的数组包含 String.Empty 表示标点符号和空格字符之间的空子字符串匹配的值。

注解

当字符串由一组已知的字符串分隔时,可以使用 Split 该方法将其分隔为子字符串。

分隔符字符串不包括在返回数组的元素中。 例如,如果 separator 数组包含字符串“--”,并且当前字符串实例的值为“aa--bb--cc”,该方法将返回包含三个元素的数组:“aa”、“bb”和“cc”。

如果此实例不包含任何字符串 separator,则返回的数组由包含此实例的单个元素组成。

options如果参数为RemoveEmptyEntries零且此实例的长度为零,则该方法返回一个空数组。

每个元素 separator 定义由一个或多个字符组成的单独分隔符。 options如果参数是None,并且两个分隔符是相邻的,或者在此实例的开头或末尾找到一个分隔符,则相应的数组元素包含String.Empty。 例如,如果separator包含两个元素“-”和“_”,则字符串实例的值为“-_aa-_”,并且参数的值为None,该方法将返回具有以下五个元素的options字符串数组:

  1. String.Empty,表示索引 0 处“-”子字符串前面的空字符串。

  2. String.Empty,表示索引 0 处的“-”子字符串与索引 1 处的“_”子字符串之间的空字符串。

  3. “aa”。

  4. String.Empty,表示索引 4 处“-”子字符串后面的空字符串。

  5. String.Empty,表示索引 5 处“_”子字符串后面的空字符串。

分隔符数组

如果其中 separator 任一元素由多个字符组成,则整个子字符串被视为分隔符。 例如,如果其中一个元素 separator 为“10”,则尝试拆分字符串“This10is10a10string”。

separator如果参数为null或不包含非空字符串,则假定空格字符为分隔符。 空格字符由 Unicode 标准定义,如果 Char.IsWhiteSpace 方法传递给该字符,则返回 true 这些字符。

若要为参数传递null,必须指示要消除其他重载(例如Split(Char[], StringSplitOptions))的调用的歧义的类型nullstring[] separator 以下示例演示了几种明确标识此重载的方法。

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忽略其值为null或空字符串(“)的任何元素separator

为避免当字符串 separator 具有常见字符时出现不明确的结果,该 Split 作从实例值的开头到末尾开始,并将该元素中的 separator 第一个元素与实例中的分隔符匹配。 实例中遇到子字符串的顺序优先于元素的顺序 separator

例如,请考虑其值为“abcdef”的实例。 如果第一个元素是“ef”,第二个元素 separator 是“bcde”,则拆分作的结果将是包含两个元素“a”和“f”的字符串数组。 这是因为遇到实例“bcde”中的子字符串,并在遇到子字符串“f”之前匹配元素 separator

但是,如果第一个元素是“bcd”,第二个元素 separator 是“bc”,则拆分作的结果将是包含两个元素“a”和“ef”的字符串数组。 这是因为“bcd”是第一个与实例中的分隔符匹配的分隔符 separator 。 如果分隔符的顺序被反转,因此第一个元素为“bc”,第二个元素为“bcd”,则结果将是包含两个元素“a”和“def”的字符串数组。

性能注意事项

这些 Split 方法为返回的数组对象分配内存,并为每个数组元素分配一个 String 对象。 如果应用程序需要最佳性能,或者如果管理内存分配在应用程序中至关重要,请考虑使用 IndexOfIndexOfAny 方法(可选 Compare )在字符串中查找子字符串。

如果要在分隔符处拆分字符串,请使用 IndexOfIndexOfAny 方法在字符串中找到分隔符。 如果要在分隔符字符串中拆分字符串,请使用 IndexOfIndexOfAny 方法查找分隔符字符串的第一个字符。 然后,使用 Compare 该方法确定第一个字符之后的字符是否等于分隔符字符串的剩余字符。

此外,如果使用同一组字符在多个 Split 方法调用中拆分字符串,请考虑在每个方法调用中创建一个数组并引用它。 这大大减少了每个方法调用的额外开销。

调用方说明

在 .NET Framework 3.5 和更早版本中,如果Split(Char[])方法传递separatornull的是或不包含任何字符,则该方法使用略有不同的空格字符集来拆分字符串,而不是Trim(Char[])该方法剪裁字符串。 从 .NET Framework 4 开始,这两种方法都使用相同的 Unicode 空格字符集。

适用于

Split(String, Int32, StringSplitOptions)

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
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[]

一个数组,该数组包含此实例中由该实例分隔的separator最多count子字符串。

注解

如果字符串已被拆分 count - 1 次,但尚未到达字符串的末尾,则返回的数组中的最后一个字符串将包含此实例的剩余尾随子字符串(未更改)。

适用于

Split(Char[], StringSplitOptions)

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
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-_”,并且参数的值为None,则该方法返回具有以下五个元素的options字符串数组:

  1. String.Empty,表示索引 0 处“-”字符前面的空字符串。

  2. String.Empty,表示索引 0 处的“-”字符和索引 1 处的“_”字符之间的空字符串。

  3. “aa”。

  4. String.Empty,表示索引 4 处“-”字符后面的空字符串。

  5. String.Empty,表示索引 5 处“_”字符后面的空字符串。

分隔符数组

separator如果参数不null包含任何字符,则假定空格字符为分隔符。 空格字符由 Unicode 标准定义,如果 Char.IsWhiteSpace 方法传递给该字符,则返回 true 这些字符。

若要为参数传递null,必须指示要消除其他重载(例如Split(String[], StringSplitOptions))的调用的歧义的类型nullchar[] separator 以下示例演示了几种明确标识此重载的方法。

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 对象。 如果应用程序需要最佳性能,或者如果管理内存分配在应用程序中至关重要,请考虑使用 IndexOfIndexOfAny 方法(可选 Compare )在字符串中查找子字符串。

如果要在分隔符处拆分字符串,请使用 IndexOfIndexOfAny 方法在字符串中找到分隔符。 如果要在分隔符字符串中拆分字符串,请使用 IndexOfIndexOfAny 方法查找分隔符字符串的第一个字符。 然后,使用 Compare 该方法确定第一个字符之后的字符是否等于分隔符字符串的剩余字符。

此外,如果使用同一组字符在多个 Split 方法调用中拆分字符串,请考虑在每个方法调用中创建一个数组并引用它。 这大大减少了每个方法调用的额外开销。

调用方说明

在 .NET Framework 3.5 和更早版本中,如果Split(Char[])方法传递separatornull的是或不包含任何字符,则该方法使用略有不同的空格字符集来拆分字符串,而不是Trim(Char[])该方法剪裁字符串。 从 .NET Framework 4 开始,这两种方法都使用相同的 Unicode 空格字符集。

适用于

Split(Char[], Int32)

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
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包含任何字符,则假定空格字符为分隔符。 空格字符由 Unicode 标准定义,如果 Char.IsWhiteSpace 方法传递给该字符,则返回 true 这些字符。

每个元素 separator 定义单独的分隔符字符。 如果两个分隔符相邻,或者在此实例的开头或末尾找到分隔符,则相应的数组元素包含 Empty

如果此实例中有多个count子字符串,则返回值的第一个元素中返回第一count - 1count - 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[] {'.'} {“Banana”}
Visual Basic “香蕉” Char() = {“.”c} {“Banana”}
C# “达布\n斯马巴” new Char[] {} {“Darb”, “Smarba”}
Visual Basic “Darb” & vbLf 和 “Smarba” Char() = {} {“Darb”, “Smarba”}
C# “达布\n斯马巴” null {“Darb”, “Smarba”}
Visual Basic “Darb” & vbLf 和 “Smarba” {“Darb”, “Smarba”}

性能注意事项

这些 Split 方法为返回的数组对象分配内存,并为每个数组元素分配一个 String 对象。 如果应用程序需要最佳性能,或者如果管理内存分配在应用程序中至关重要,请考虑使用 IndexOfIndexOfAny 方法(可选 Compare )在字符串中查找子字符串。

如果要在分隔符处拆分字符串,请使用 IndexOfIndexOfAny 方法在字符串中找到分隔符。 如果要在分隔符字符串中拆分字符串,请使用 IndexOfIndexOfAny 方法查找分隔符字符串的第一个字符。 然后,使用 Compare 该方法确定第一个字符之后的字符是否等于分隔符字符串的剩余字符。

此外,如果使用同一组字符在多个 Split 方法调用中拆分字符串,请考虑在每个方法调用中创建一个数组并引用它。 这大大减少了每个方法调用的额外开销。

调用方说明

在 .NET Framework 3.5 和更早版本中,如果Split(Char[])方法传递separatornull的是或不包含任何字符,则该方法使用略有不同的空格字符集来拆分字符串,而不是Trim(Char[])该方法剪裁字符串。 从 .NET Framework 4 开始,这两种方法都使用相同的 Unicode 空格字符集。

另请参阅

适用于

Split(Char, StringSplitOptions)

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
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>)

Source:
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[])

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
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[] {'.'} {“Banana”}
Visual Basic “香蕉” Char() = {“.”c} {“Banana”}
C# “达布\n斯马巴” new Char[] {} {“Darb”, “Smarba”}
Visual Basic “Darb” & vbLf 和 “Smarba” Char() = {} {“Darb”, “Smarba”}
C# “达布\n斯马巴” null {“Darb”, “Smarba”}
Visual Basic “Darb” & vbLf 和 “Smarba” {“Darb”, “Smarba”}

分隔符数组

分隔符的每个元素定义一个单独的分隔符,该分隔符由一个字符组成。

separator如果参数为null或不包含任何字符,该方法会将空格字符视为分隔符。 空格字符由 Unicode 标准定义,如果向该标准传递空格字符,该方法 Char.IsWhiteSpacetrue 返回该方法。

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 修饰,因此编译器会将单个字符解释为单元素字符数组。 对于包含separator参数的其他String.Split重载来说,情况并非如此;必须将这些重载显式传递为字符数组作为separator参数。

比较详细信息

该方法 Split(Char[]) 提取此字符串中的子字符串,这些子字符串由数组中的 separator 一个或多个字符分隔,并将这些子字符串作为数组的元素返回。

该方法 Split(Char[]) 通过使用区分大小写的序号排序规则执行比较来查找分隔符。 有关单词、字符串和序号排序的详细信息,请参阅 System.Globalization.CompareOptions 枚举。

性能注意事项

这些 Split 方法为返回的数组对象分配内存,并为每个数组元素分配一个 String 对象。 如果应用程序需要最佳性能,或者管理内存分配在应用程序中至关重要,请考虑使用 IndexOfIndexOfAny 方法。 还可以选择使用 Compare 该方法在字符串中查找子字符串。

若要在分隔符处拆分字符串,请使用 IndexOfIndexOfAny 方法在字符串中找到分隔符。 若要在分隔符字符串处拆分字符串,请使用 IndexOfIndexOfAny 方法查找分隔符字符串的第一个字符。 然后,使用 Compare 该方法确定第一个字符之后的字符是否等于分隔符字符串的剩余字符。

此外,如果使用同一组字符在多个 Split 方法调用中拆分字符串,请考虑在每个方法调用中创建一个数组并引用它。 这大大减少了每个方法调用的额外开销。

调用方说明

在 .NET Framework 3.5 和更早版本中,如果Split(Char[])方法传递separatornull的是或不包含任何字符,则该方法使用略有不同的空格字符集来拆分字符串,而不是Trim(Char[])该方法剪裁字符串。 从 .NET Framework 4 开始,这两种方法都使用相同的 Unicode 空格字符集。

另请参阅

适用于

Split(String, StringSplitOptions)

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
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的子字符串。

适用于