String.Split 方法

定义

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

重载

Split(String, Int32, StringSplitOptions)

根据指定的分隔字符串和(可选)选项,将字符串拆分为最大数量的子字符串。

Split(Char[], Int32, StringSplitOptions)

根据指定的分隔字符和(可选)选项,将字符串拆分为最大数量的子字符串。

Split(Char, Int32, StringSplitOptions)

根据指定的分隔符和(可选)选项,将字符串拆分为最大数量的子字符串。 根据提供的字符分隔符将字符串拆分为最大子字符串数,可以选择省略结果中的空子字符串。

Split(String[], StringSplitOptions)

根据指定的分隔字符串以及(可选)选项将字符串拆分为子字符串。

Split(String, StringSplitOptions)

将字符串拆分为基于提供的字符串分隔符的子字符串。

Split(Char[])

根据指定的分隔字符将字符串拆分为子字符串。

Split(Char[], Int32)

根据指定的分隔字符将字符串拆分为最大数量的子字符串。

Split(Char, StringSplitOptions)

根据指定的分隔符以及(可选)选项将字符串拆分为子字符串。

Split(ReadOnlySpan<Char>)

根据指定的分隔字符将字符串拆分为子字符串。

Split(String[], Int32, StringSplitOptions)

根据指定的分隔字符串和(可选)选项,将字符串拆分为最大子字符串数。

Split(Char[], StringSplitOptions)

根据指定的分隔字符和选项将字符串拆分为子字符串。

注解

Split 用于将带分隔符的字符串分解为子字符串。 可以使用字符数组或字符串数组来指定零个或多个分隔符或字符串。 如果未指定分隔字符,字符串将拆分为空白字符。

Split 方法的重载允许限制方法返回的子字符串数(Split(Char[], Int32) 方法),以指定是在结果中包含空字符串和/或剪裁子字符串(Split(Char[], StringSplitOptions)Split(String[], StringSplitOptions) 方法),还是同时执行(Split(Char[], Int32, StringSplitOptions)Split(String[], Int32, StringSplitOptions) 方法)。

提示

Split 方法并不总是将带分隔符的字符串分解为子字符串的最佳方法。 如果不想提取分隔字符串的所有子字符串,或者要基于模式而不是一组分隔符来分析字符串,请考虑使用正则表达式,或组合返回字符索引的搜索方法之一和 Substring 方法。 有关详细信息,请参阅 从字符串中提取子字符串。

以下示例显示了三个不同的 String.Split()重载。 第一个示例调用 Split(Char[]) 重载并传入单个分隔符。

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

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

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

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

let subs = s.Split ' '

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

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

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

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

可以看到,句点字符(.)包含在两个子字符串中。 如果要排除句点字符,可以将句点字符添加为附加分隔符。 下一个示例演示如何执行此操作。

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

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

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

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

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

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

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

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

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

这些句点从子字符串中消失,但现在包含两个额外的空子字符串。 这些空子字符串表示单词与后面的句点之间的子字符串。 若要从生成的数组中省略空子字符串,可以调用 Split(Char[], StringSplitOptions) 重载并为 options 参数指定 StringSplitOptions.RemoveEmptyEntries

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

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

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

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

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

/*
This example produces the following results:

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

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

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

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

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

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

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

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

string phrase = "The quick  brown fox";

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

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

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

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

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

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

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

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

如果 count 参数为零,或者 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

根据指定的分隔符和(可选)选项,将字符串拆分为最大数量的子字符串。 根据提供的字符分隔符将字符串拆分为最大子字符串数,可以选择省略结果中的空子字符串。

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

根据指定的分隔字符串以及(可选)选项将字符串拆分为子字符串。

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

参数

separator
String[]

一个字符串数组,用于分隔此字符串中的子字符串、不包含分隔符或 null的空数组。

options
StringSplitOptions

枚举值的按位组合,指定是否剪裁子字符串并包括空子字符串。

返回

String[]

一个数组,其元素包含此字符串中的子字符串,这些子字符串由 separator中的一个或多个字符串分隔。 有关详细信息,请参阅“备注”部分。

属性

例外

options 不是 StringSplitOptions 值之一。

示例

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

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

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

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

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

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

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

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

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

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

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

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

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

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

以下示例定义一个分隔符数组,其中包括标点符号和空格字符。 将此数组与 StringSplitOptions.RemoveEmptyEntries 的值一起传递给 Split(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

请注意,该方法调用时 options 参数设置为 StringSplitOptions.RemoveEmptyEntries。 这可以防止返回的数组包括表示标点符号和空格字符之间的空子字符串匹配的 String.Empty 值。

注解

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

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

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

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

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

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

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

  3. “aa”。

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

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

分隔符数组

如果 separator 中的任何元素都由多个字符组成,则整个子字符串被视为分隔符。 例如,如果 separator 中的某个元素为“10”,则尝试拆分字符串“This10is10a10string”。返回以下四个元素数组:{ “This”、“is”、“a”、“string”。}。

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

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

string phrase = "The quick  brown fox";

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

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

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

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

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

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

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

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

比较详细信息

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

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

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

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

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

但是,如果 separator 的第一个元素为“bcd”,第二个元素为“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, StringSplitOptions)

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分隔的此实例中的子字符串。

适用于

Split(Char[])

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斯马巴” {“Darb”, “Smarba”}
Visual Basic “Darb”& vbLf & “Smarba” {“Darb”, “Smarba”}

分隔符数组

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

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

String.Split(Char[]) 和编译器重载解析

尽管此重载 String.Split 的单个参数是字符数组,但可以使用单个字符调用它,如以下示例所示。

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

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

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

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

由于 separator 参数使用 ParamArrayAttribute 属性进行修饰,因此编译器会将单个字符解释为单元素字符数组。 对于包含 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(Char[], Int32)

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 - 1 元素中返回第一个 count - 1 子字符串,并且此实例中的剩余字符在返回值的最后一个元素中返回。

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

下表显示了一些示例。

语言 字符串值 分隔符 返回的数组
C# "42, 12, 19" new Char[] {',', '} {"42", "", "12", "", "19"}
Visual Basic "42, 12, 19" Char() = {“,”c, “ ”c}) {"42", "", "12", "", "19"}
C# "42..12..19." new Char[] {'.'} {"42", "", "12", "", "19", ""}
Visual Basic "42..12..19." Char() = {“.”c} {"42", "", "12", "", "19", ""}
C# “香蕉” new Char[] {'.'} {“Banana”}
Visual Basic “香蕉” Char() = {“.”c} {“Banana”}
C# “达布\n斯马巴” new Char[] {} {“Darb”, “Smarba”}
Visual Basic “Darb”& vbLf & “Smarba” Char() = {} {“Darb”, “Smarba”}
C# “达布\n斯马巴” {“Darb”, “Smarba”}
Visual Basic “Darb”& vbLf & “Smarba” {“Darb”, “Smarba”}

性能注意事项

Split 方法为返回的数组对象分配内存,并为每个数组元素分配 String 对象。 如果应用程序需要最佳性能,或者管理内存分配在应用程序中至关重要,请考虑使用 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

根据指定的分隔符以及(可选)选项将字符串拆分为子字符串。

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

根据指定的分隔字符将字符串拆分为子字符串。

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

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

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

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

/*
This example produces the following results:

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

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

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

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

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

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

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

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

string phrase = "The quick  brown fox";

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

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

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

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

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

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

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

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

如果 count 参数为零,或者 options 参数 RemoveEmptyEntries 且此实例的长度为零,则返回空数组。

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

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

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

分隔符数组

如果 separator 中的任何元素都由多个字符组成,则整个子字符串被视为分隔符。 例如,如果 separator 中的某个元素为“10”,则尝试拆分字符串“This10is10a10string”。返回以下四个元素数组:{ “This”、“is”、“a”、“string”。}。

比较详细信息

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

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

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

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

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

但是,如果 separator 的第一个元素为“bcd”,第二个元素为“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(Char[], StringSplitOptions)

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

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

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

/*
This example produces the following results:

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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


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

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

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

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

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

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

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


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

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

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

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


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

/*
This example produces the following results:

1) Split a string delimited by characters:

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

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

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

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

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

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

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

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

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

2) Split a string delimited by another string:

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

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

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

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

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

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

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

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

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

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

// Display the array of separated strings using a local function
let show  (entries: string[]) =
    printfn $"The return value contains these {entries.Length} elements:"
    for entry in entries do
        printf $"<{entry}>"
    printf "\n\n"

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

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

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

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

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

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

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


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

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

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

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


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

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

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

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

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

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

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


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

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

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

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

(*
This example produces the following results:

1) Split a string delimited by characters:

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

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

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

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

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

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

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

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

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

2) Split a string delimited by another string:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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


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

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


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

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

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

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

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


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

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

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

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

End Sub

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

End Sub

'This example produces the following results:
'
' 1) Split a string delimited by characters:
'
' The original string is: ",ONE,, TWO,, , THREE,,".
' The delimiter character is: ','.
'
' 1a) Return all elements:
' The return value contains these 9 elements:
' <><ONE><>< TWO><>< >< THREE><><>
'
' 1b) Return all elements with whitespace trimmed:
' The return value contains these 9 elements:
' <><ONE><><TWO><><><THREE><><>
'
' 1c) Return all non-empty elements:
' The return value contains these 4 elements:
' <ONE>< TWO>< >< THREE>
'
' 1d) Return all non-whitespace elements with whitespace trimmed:
' The return value contains these 3 elements:
' <ONE><TWO><THREE>
'
' 1e) Split into only two elements:
' The return value contains these 2 elements:
' <><ONE,, TWO,, , THREE,,>
'
' 1f) Split into only two elements with whitespace trimmed:
' The return value contains these 2 elements:
' <><ONE,, TWO,, , THREE,,>
'
' 1g) Split into only two non-empty elements:
' The return value contains these 2 elements:
' <ONE>< TWO,, , THREE,,>
'
' 1h) Split into only two non-whitespace elements with whitespace trimmed:
' The return value contains these 2 elements:
' <ONE><TWO,, , THREE,,>
'
' 2) Split a string delimited by another string:
'
' The original string is: "[stop]ONE[stop] [stop]TWO  [stop][stop]  [stop]THREE[stop][stop]  ".
' The delimiter string is: "[stop]".
'
' 2a) Return all elements:
' The return value contains these 9 elements:
' <><ONE>< ><TWO  ><><  ><THREE><><  >
'
' 2b) Return all elements with whitespace trimmed:
' The return value contains these 9 elements:
' <><ONE><><TWO><><><THREE><><>
'
' 2c) Return all non-empty elements:
' The return value contains these 6 elements:
' <ONE>< ><TWO  ><  ><THREE><  >
'
' 2d) Return all non-whitespace elements with whitespace trimmed:
' The return value contains these 3 elements:
' <ONE><TWO><THREE>
'
' 2e) Split into only two elements:
' The return value contains these 2 elements:
' <><ONE[stop] [stop]TWO  [stop][stop]  [stop]THREE[stop][stop]  >
'
' 2f) Split into only two elements with whitespace trimmed:
' The return value contains these 2 elements:
' <><ONE[stop] [stop]TWO  [stop][stop]  [stop]THREE[stop][stop]>
'
' 2g) Split into only two non-empty elements:
' The return value contains these 2 elements:
' <ONE>< [stop]TWO  [stop][stop]  [stop]THREE[stop][stop]  >
'
' 2h) Split into only two non-whitespace elements with whitespace trimmed:
' The return value contains these 2 elements:
' <ONE><TWO  [stop][stop]  [stop]THREE[stop][stop]>
'

注解

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

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

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

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

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

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

  3. “aa”。

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

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

分隔符数组

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

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

string phrase = "The quick  brown fox";

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

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

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

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

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

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

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

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

比较详细信息

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

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

性能注意事项

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

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

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

调用方说明

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

适用于