String.Split 方法

定义

返回的字符串数组包含此实例中的子字符串(由指定字符串或 Unicode 字符数组的元素分隔)。

重载

Split(Char[])

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

Split(Char, StringSplitOptions)

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

Split(Char[], Int32)

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

Split(Char[], StringSplitOptions)

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

Split(String, StringSplitOptions)

根据提供的字符串分隔符将字符串拆分为多个子字符串。

Split(String[], StringSplitOptions)

基于指定的分隔字符串和(可选)选项将字符串拆分为子字符串。

Split(Char, Int32, StringSplitOptions)

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

Split(Char[], Int32, StringSplitOptions)

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

Split(String, Int32, StringSplitOptions)

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

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

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

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

下表展示了一些示例。

语言 字符串值 Separator 返回的数组
C# "42, 12, 19" new Char[] {',', '} {"42", "", "12", "", "19"}
Visual Basic "42, 12, 19" Char () = {“,”c, “ ”c}) {"42", "", "12", "", "19"}
C# "42..12..19." new Char[] {'.'} {"42", "", "12", "", "19", ""}
Visual Basic "42..12..19." Char () = {“.”c} {"42", "", "12", "", "19", ""}
C# “Banana” new Char[] {'.'} {“Banana”}
Visual Basic “Banana” Char () = {“.”c} {“Banana”}
C# “Darb\nSmarba” new Char[] {} {“Darb”, “Smarba”}
Visual Basic “Darb” & vbLf & “Smarba” Char () = {} {“Darb”, “Smarba”}
C# “Darb\nSmarba” Null {“Darb”, “Smarba”}
Visual Basic “Darb” & vbLf & “Smarba” {“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, StringSplitOptions)

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

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

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

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(Nothing, 2)
Dim firstName As String = substrings(0)
Dim lastName As String

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

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

注解

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

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

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

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

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

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

下表展示了一些示例。

语言 字符串值 Separator 返回的数组
C# "42, 12, 19" new Char[] {',', '} {"42", "", "12", "", "19"}
Visual Basic "42, 12, 19" Char () = {“,”c, “ ”c}) {"42", "", "12", "", "19"}
C# "42..12..19." new Char[] {'.'} {"42", "", "12", "", "19", ""}
Visual Basic "42..12..19." Char () = {“.”c} {"42", "", "12", "", "19", ""}
C# “Banana” new Char[] {'.'} {“Banana”}
Visual Basic “Banana” Char () = {“.”c} {“Banana”}
C# “Darb\nSmarba” new Char[] {} {“Darb”, “Smarba”}
Visual Basic “Darb” & vbLf & “Smarba” Char () = {} {“Darb”, “Smarba”}
C# “Darb\nSmarba” Null {“Darb”, “Smarba”}
Visual Basic “Darb” & vbLf & “Smarba” {“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)

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

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.
string s1 = ",ONE,,TWO,,,THREE,,";
string s2 = "[stop]" +
            "ONE[stop][stop]" +
            "TWO[stop][stop][stop]" +
            "THREE[stop][stop]";
char[] charSeparators = new char[] { ',' };
string[] stringSeparators = new string[] { "[stop]" };
string[] result;
// ------------------------------------------------------------------------------
// Split a string delimited by characters.
// ------------------------------------------------------------------------------
Console.WriteLine("1) Split a string delimited by characters:\n");

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

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

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

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

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

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

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

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

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

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

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

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

/*
This example produces the following results:

1) Split a string delimited by characters:

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

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

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

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

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

2) Split a string delimited by another string:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

(*
This example produces the following results:

1) Split a string delimited by characters:

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

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

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

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

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

2) Split a string delimited by another string:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

End Sub


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

End Sub

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

注解

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

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

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

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

  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

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

string phrase = "The quick  brown fox";

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

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

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

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

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

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

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

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

比较详细信息

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

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

性能注意事项

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

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

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

调用方说明

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

适用于

Split(String, StringSplitOptions)

根据提供的字符串分隔符将字符串拆分为多个子字符串。

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

基于指定的分隔字符串和(可选)选项将字符串拆分为子字符串。

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

参数

separator
String[]

分隔此字符串中子字符串的字符串数组、不包含分隔符的空数组或 null

options
StringSplitOptions

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

返回

String[]

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

属性

例外

options 不是 StringSplitOptions 值之一。

示例

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

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

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

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

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

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

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

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

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

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

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

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

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

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

以下示例定义包含标点符号和空格字符的分隔符数组。 将此数组与 值 StringSplitOptions.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-_”,参数Noneoptions值为 ,该方法返回包含以下五个元素的字符串数组:

  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.”}。

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

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

string phrase = "The quick  brown fox";

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

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

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

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

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

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

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

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

比较详细信息

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

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

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

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

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

但是,如果 的第一个元素 separator 为“bcd”,第二个元素为“bcd”,则拆分操作的结果将是包含两个元素“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, Int32, StringSplitOptions)

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

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

参数

separator
Char

一个字符,用于分隔此实例中的子字符串。

count
Int32

数组中预期的最大元素数。

options
StringSplitOptions

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

返回

String[]

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

注解

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

适用于

Split(Char[], Int32, StringSplitOptions)

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

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.
string s1 = ",ONE,,TWO,,,THREE,,";
string s2 = "[stop]" +
            "ONE[stop][stop]" +
            "TWO[stop][stop][stop]" +
            "THREE[stop][stop]";
char[] charSeparators = new char[] { ',' };
string[] stringSeparators = new string[] { "[stop]" };
string[] result;
// ------------------------------------------------------------------------------
// Split a string delimited by characters.
// ------------------------------------------------------------------------------
Console.WriteLine("1) Split a string delimited by characters:\n");

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

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

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

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

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

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

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

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

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

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

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

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

/*
This example produces the following results:

1) Split a string delimited by characters:

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

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

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

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

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

2) Split a string delimited by another string:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

(*
This example produces the following results:

1) Split a string delimited by characters:

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

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

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

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

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

2) Split a string delimited by another string:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

End Sub


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

End Sub

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

注解

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

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

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

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

string phrase = "The quick  brown fox";

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

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

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

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

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

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

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

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

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

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

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

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

性能注意事项

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

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

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

调用方说明

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

适用于

Split(String, Int32, StringSplitOptions)

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

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

参数

separator
String

一个字符串,用于分隔此实例中的子字符串。

count
Int32

数组中预期的最大元素数。

options
StringSplitOptions

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

返回

String[]

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

注解

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

适用于

Split(String[], Int32, StringSplitOptions)

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

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.
string s1 = ",ONE,,TWO,,,THREE,,";
string s2 = "[stop]" +
            "ONE[stop][stop]" +
            "TWO[stop][stop][stop]" +
            "THREE[stop][stop]";
char[] charSeparators = new char[] { ',' };
string[] stringSeparators = new string[] { "[stop]" };
string[] result;
// ------------------------------------------------------------------------------
// Split a string delimited by characters.
// ------------------------------------------------------------------------------
Console.WriteLine("1) Split a string delimited by characters:\n");

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

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

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

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

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

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

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

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

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

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

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

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

/*
This example produces the following results:

1) Split a string delimited by characters:

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

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

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

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

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

2) Split a string delimited by another string:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

(*
This example produces the following results:

1) Split a string delimited by characters:

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

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

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

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

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

2) Split a string delimited by another string:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

End Sub


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

End Sub

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

注解

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

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

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

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

string phrase = "The quick  brown fox";

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

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

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

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

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

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

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

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

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

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

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

如果 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 空格字符集。

适用于