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) 多載並指定 StringSplitOptions.RemoveEmptyEntries 做為 options 參數。

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

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

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

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

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

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

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

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

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

個別多載 String.Split() 的區段包含進一步的範例。

Split(Char[])

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs

根據指定的分隔字元,將一個字串分割成數個子字串。

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

參數

separator
Char[]

分隔字元的陣列、不包含分隔符號的空陣列,或 null

傳回

String[]

陣列,其項目中包含了這個執行個體中的子字串,由 separator 內的一或多個字元分隔。 如需詳細資訊,請參閱<備註>一節。

範例

下列範例示範如何藉由將空格字元 () 和製表元 \t () 視為分隔符,從文本塊中擷取個別字組。 要分割的字串包含這兩個字元。

string s = "Today\tI'm going to school";
string[] subs = s.Split(' ', '\t');

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

// This example produces the following output:
//
// Substring: Today
// Substring: I'm
// Substring: going
// Substring: to
// Substring: school
let s = "Today\tI'm going to school"
let subs = s.Split(' ', '\t')

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

// This example produces the following output:
//
// Substring: Today
// Substring: I'm
// Substring: going
// Substring: to
// Substring: school
Dim s As String = "Today" & vbTab & "I'm going to school"
Dim subs As String() = s.Split(" "c, Char.Parse(vbTab))

For Each substring In subs
    Console.WriteLine("Substring: " & substring)
Next

' This example produces the following output:
'
' Substring: Today
' Substring: I 'm
' Substring: going
' Substring: to
' Substring: school

備註

當字串以一組已知的字元分隔時,您可以使用 Split(Char[]) 方法將它分隔成子字串。

傳回數位的專案中不包含分隔符。 例如,如果分隔符陣列包含字元 「-」,且目前字串實例的值是 「aa-bb-cc」,則方法會傳回包含三個元素的陣列:「aa」。、“bb” 和 “cc”。

如果這個實例不包含 中的任何 separator字元,則傳回的陣列是由包含這個實例的單一元素所組成。

的每個元素 separator 都會定義個別的分隔符。 如果兩個分隔符相鄰,或在這個實體的開頭或結尾找到分隔符,則傳回數位中的對應專案會 Empty包含 。

下表提供一些範例。

Language 字串值 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# 「水果」 new Char[] {'.'} {“Banana”}
Visual Basic 「水果」 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” Nothing {“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[])方法傳遞separator的 為 null 或 不包含任何字元,則方法會使用稍有不同的空格符集來分割字串,而不是Trim(Char[])方法修剪字元串。 從 .NET Framework 4 開始,這兩種方法都會使用相同的 Unicode 空格符集。

另請參閱

適用於

Split(Char, StringSplitOptions)

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs

根據指定的分隔字元和選擇性選項,將一個字串分割成數個子字串。

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

參數

separator
Char

此字串中分隔子字串的字元。

options
StringSplitOptions

列舉值的位元組合,可指定是否要修剪子字串並包含空的子字串。

傳回

String[]

陣列,其元素包含來自此執行個體的子字串,以 separator 分隔。

適用於

Split(Char[], Int32)

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs

根據指定的分隔字元,將一個字串分割成最多的子字串。

public:
 cli::array <System::String ^> ^ Split(cli::array <char> ^ separator, int count);
public string[] Split (char[] separator, int count);
public string[] Split (char[]? separator, int count);
member this.Split : char[] * int -> string[]
Public Function Split (separator As Char(), count As Integer) As String()

參數

separator
Char[]

在此字串中分隔數個子字串的字元陣列、不包含分隔符號的空陣列、或 null

count
Int32

要傳回的子字串之最大數目。

傳回

String[]

陣列,其項目中包含了這個執行個體中的子字串,由 separator 內的一或多個字元分隔。 如需詳細資訊,請參閱<備註>一節。

例外狀況

count 為負。

範例

下列範例示範如何使用 count 來限制 所 Split傳回的字串數目。

string name = "Alex Johnson III";

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

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

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

let subs = name.Split(null, 2)

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

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

Dim substrings = name.Split(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 - 1count - 1個子字串,而這個實例中的其餘字元則會傳回傳回值的最後一個元素。

如果 count 大於子字串的數目,則會傳回可用的子字串,而且不會擲回例外狀況。

下表提供一些範例。

Language 字串值 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# “Ana” new Char[] {'.'} {“Ana”}
Visual Basic “Ana” Char () = {“.”c} {“Ana”}
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” Nothing {“Darb”, “Smarba”}

效能考量

方法會 Split 為傳回的陣列物件配置記憶體,以及 String 每個數位專案的物件。 如果您的應用程式需要最佳效能,或管理記憶體配置在應用程式中很重要,請考慮使用 IndexOfIndexOfAny 方法,並選擇性 Compare 地在字串內尋找子字串。

如果您要在分隔字元上分割字串,請使用 IndexOfIndexOfAny 方法來找出字元串中的分隔符。 如果您要在分隔符字串上分割字串,請使用 IndexOfIndexOfAny 方法來找出分隔符字串的第一個字元。 Compare然後使用 方法來判斷第一個字元之後的字元是否等於分隔符字串的其餘字元。

此外,如果使用相同的字元集來分割多個 Split 方法呼叫中的字串,請考慮建立單一陣列,並在每個方法呼叫中參考它。 這可大幅減少每個方法呼叫的額外負荷。

給呼叫者的注意事項

在 .NET Framework 3.5 和舊版中,如果Split(Char[])方法傳遞separator了 ,null或不包含任何字元,則方法會使用稍微不同的空格符集來分割字串,而不是Trim(Char[])方法修剪字元串。 從 .NET Framework 4 開始,這兩種方法都會使用相同的 Unicode 空格符集。

另請參閱

適用於

Split(Char[], StringSplitOptions)

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs

根據指定的分隔字元和選項,將一個字串分割成數個子字串。

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

參數

separator
Char[]

在此字串中分隔數個子字串的字元陣列、不包含分隔符號的空陣列、或 null

options
StringSplitOptions

列舉值的位元組合,可指定是否要修剪子字串並包含空的子字串。

傳回

String[]

陣列,其項目包含了這個字串中由 separator 內的一或多個字元所分隔的子字串。 如需詳細資訊,請參閱<備註>一節。

屬性

例外狀況

options 不是其中一個 StringSplitOptions 值。

範例

下列範例會 StringSplitOptions 使用 列舉來包含或排除 方法所產生的 Split 子字串。

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

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

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

/*
This example produces the following results:

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

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

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

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

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

*/
// This example demonstrates the String.Split() methods that use
// the StringSplitOptions enumeration.
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-_”,而自變數的值是 None,則方法會傳回具有下列五個元素的options字元串陣列:

  1. String.Empty,表示位於索引 0 之 「-」 字元前面的空字串。

  2. String.Empty,表示索引 0 的 “-” 字元與索引 1 之 “_” 字元之間的空字串。

  3. “aa”。

  4. String.Empty,表示位於索引 4 之 「-」 字元後面的空字串。

  5. String.Empty,表示位於索引 5 之 “_” 字元後面的空字串。

分隔符陣列

separator如果 參數為 null 或 不包含任何字元,則會假設空格符為分隔符。 空白元是由 Unicode 標準所定義,如果 Char.IsWhiteSpace 方法傳遞至該字元,則會傳回 true

若要為 參數傳遞 null ,您必須指出 的null型別,以釐清呼叫與其他一些多載,例如 Split(String[], StringSplitOptions)char[] separator 下列範例示範數種方式,明確識別此多載。

string phrase = "The quick  brown fox";

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

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

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

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

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

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

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

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

比較詳細數據

方法 Split 會擷取這個字串中的子字串,這個字串是以 參數中的 separator 一或多個字元分隔,並傳回這些子字串做為陣列的專案。

方法會 Split 藉由使用區分大小寫的序數排序規則來執行比較來尋找分隔符。 如需字組、字串和序數排序的詳細資訊,請參閱 System.Globalization.CompareOptions 列舉。

效能考量

方法 Split 會為傳回的陣列物件配置記憶體,以及 String 每個數位專案的物件。 如果您的應用程式需要最佳效能,或如果管理記憶體配置在您的應用程式中很重要,請考慮使用 IndexOfIndexOfAny 方法,並選擇性地 Compare 在字串內尋找子字串串。

如果您要在分隔符上分割字串,請使用 IndexOfIndexOfAny 方法來找出字元串中的分隔符。 如果您要在分隔符字串上分割字串,請使用 IndexOfIndexOfAny 方法來找出分隔符字串的第一個字元。 Compare然後使用 方法來判斷該第一個字元後面的字元是否等於分隔符字串的其餘字元。

此外,如果使用相同的字元集來分割多個 Split 方法呼叫中的字串,請考慮建立單一陣列,並在每個方法呼叫中參考它。 這可大幅減少每個方法呼叫的額外負荷。

給呼叫者的注意事項

在 .NET Framework 3.5 和舊版中,如果Split(Char[])方法傳遞separator了 ,null或不包含任何字元,則方法會使用稍微不同的空格符集來分割字串,而不是Trim(Char[])方法修剪字元串。 從 .NET Framework 4 開始,這兩種方法都會使用相同的 Unicode 空格符集。

適用於

Split(String, StringSplitOptions)

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs

根據所提供字串分隔符號將字串分割成子字串。

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

參數

separator
String

此字串中分隔子字串的字串。

options
StringSplitOptions

列舉值的位元組合,可指定是否要修剪子字串並包含空的子字串。

傳回

String[]

陣列,其元素包含來自此執行個體的子字串,以 separator 分隔。

適用於

Split(String[], StringSplitOptions)

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs

根據指定的分隔字串和選擇性選項,將一個字串分割成數個子字串。

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

參數

separator
String[]

在此字串中分隔數個子字串的字元陣列、不包含分隔符號的空陣列、或 null

options
StringSplitOptions

列舉值的位元組合,可指定是否要修剪子字串並包含空的子字串。

傳回

String[]

陣列,其項目包含了這個字串中由 separator 內的一或多個字串所分隔的子字串。 如需詳細資訊,請參閱<備註>一節。

屬性

例外狀況

options 不是其中一個 StringSplitOptions 值。

範例

下列範例說明藉由呼叫字串的 String.Split(String[], StringSplitOptions) 方法,其 options 參數等於 StringSplitOptions.NoneStringSplitOptions.RemoveEmptyEntries來傳回的數位差異。

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

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

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

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

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

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

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

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

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

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

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

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

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

下列範例會定義包含標點符號和空格符的分隔符陣列。 將這個陣列連同的值 StringSplitOptions.RemoveEmptyEntries 一起傳遞至 Split(String[], StringSplitOptions) 方法,會傳回由字串中個別字組組成的陣列。

string[] separators = { ",", ".", "!", "?", ";", ":", " " };
string value = "The handsome, energetic, young dog was playing with his smaller, more lethargic litter mate.";
string[] words = value.Split(separators, StringSplitOptions.RemoveEmptyEntries);
foreach (var word in words)
    Console.WriteLine(word);

// The example displays the following output:
//       The
//       handsome
//       energetic
//       young
//       dog
//       was
//       playing
//       with
//       his
//       smaller
//       more
//       lethargic
//       litter
//       mate
let separators = [| ","; "."; "!"; "?"; ""; ":"; " " |]
let value = "The handsome, energetic, young dog was playing with his smaller, more lethargic litter mate."
let words = value.Split(separators, StringSplitOptions.RemoveEmptyEntries)
for word in words do
    printfn $"${word}"

// The example displays the following output:
//       The
//       handsome
//       energetic
//       young
//       dog
//       was
//       playing
//       with
//       his
//       smaller
//       more
//       lethargic
//       litter
//       mate
    Dim separators() As String = {",", ".", "!", "?", ";", ":", " "}
    Dim value As String = "The handsome, energetic, young dog was playing with his smaller, more lethargic litter mate."
    Dim words() As String = value.Split(separators, StringSplitOptions.RemoveEmptyEntries)
    For Each word In words
        Console.WriteLine(word)
    Next
End Sub

' The example displays the following output:
'
'       The
'       handsome
'       energetic
'       young
'       dog
'       was
'       playing
'       with
'       his
'       smaller
'       more
'       lethargic
'       litter
'       mate

請注意,系統會呼叫 方法,並將 options 自變數設定為 StringSplitOptions.RemoveEmptyEntries。 這可防止傳回的陣列包含 String.Empty 代表標點符號與空格符之間空白子字串相符的值。

備註

當字串是以一組已知的字串分隔時,您可以使用 Split 方法將它分隔成子字串。

傳回數位的元素中不包含分隔符字串。 例如,如果 separator 數位包含字串 「--」 且目前字串實例的值是 「aa--bb--cc」,則方法會傳回包含三個元素的陣列:“aa”、“bb” 和 “cc”。

如果這個實例不包含 中的任何 separator字串,則傳回的數位是由包含這個實例的單一元素所組成。

options如果 參數為 RemoveEmptyEntries ,且此實例的長度為零,則方法會傳回空陣列。

的每個 元素 separator 都會定義由一或多個字元組成的個別分隔符。 options如果自變數是 None,而兩個分隔符是相鄰的,或在這個實例的開頭或結尾找到分隔符,則對應的陣列元素會String.Empty包含 。 例如,如果separator包含兩個元素 「-」 和 「_」,則字串實例的值是 「-_aa-_」,而自變數的值是 None,此方法會傳回具有下列五個元素的options字元串數位:

  1. String.Empty,表示位於索引0之 “-” 子字串之前的空字串。

  2. String.Empty,表示索引 0 的 「-」 子字串與索引 1 的 “_” 子字串之間的空字串。

  3. “aa”。

  4. String.Empty,表示索引 4 處 「-」 子字串後面的空字串。

  5. String.Empty,表示位於索引 5 之 “_” 子字串後面的空字串。

分隔符陣列

如果中的任何 separator 專案包含多個字元,則會將整個子字串視為分隔符。 例如,如果 中的 separator 其中一個元素是 “10”,則嘗試分割字串 “This10is10a10string”。“ 會傳回下列四個元素陣列: { ”This“、”is“、”a“、”string.“ }。

separator如果 參數為 null 或 不包含非空白字串,則會假設空格符為分隔符。 空白元是由 Unicode 標準所定義,如果 Char.IsWhiteSpace 方法傳遞至該字元,則會傳回 true

若要為 參數傳遞 null ,您必須指出 的null型別,以釐清呼叫與其他一些多載,例如 Split(Char[], StringSplitOptions)string[] separator 下列範例示範數種方式,明確識別此多載。

string phrase = "The quick  brown fox";

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

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

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

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

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

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

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

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

比較詳細數據

方法 Split 會擷取這個字串中的子字串,這些子字串是以 參數中的 separator 一或多個字串分隔,並傳回這些子字串做為陣列的專案。

方法會 Split 藉由使用區分大小寫的序數排序規則來執行比較來尋找分隔符。 如需字組、字串和序數排序的詳細資訊,請參閱 System.Globalization.CompareOptions 列舉。

方法Split會忽略其值為 null 或空字串 (“”“) 的任何專案separator

為了避免在 中的 separator 字串具有通用字元時產生模棱兩可的結果, Split 作業會從 實例值的開頭到結尾繼續,並比對 實例中的 separator 第一個元素等於 實例中的分隔符。 實例中遇到子字串的順序優先於 中的 separator項目順序。

例如,假設實例的值是 “abcdef”。 如果 中的 separator 第一個專案是 「ef」,而第二個元素是 「bcde」,則分割作業的結果會是包含兩個元素 “a” 和 “f” 的字串數位。 這是因為遇到實例 「bcde」 中的子字串,並在遇到子字串 「f」 之前比對 中的 separator 專案。

不過,如果的第一個專案是 「bcd」,而第二個元素 separator 是 「bc」,分割作業的結果會是包含兩個元素 “a” 和 “ef” 的字串數位。 這是因為 「bcd」 是 中符合 實例中 separator 分隔符的第一個分隔符。 如果分隔符的順序反轉,因此第一個專案是 “bc”,而第二個元素是 “bcd”,則結果會是包含兩個元素 “a” 和 “def” 的字符串陣列。

效能考量

方法 Split 會為傳回的陣列物件配置記憶體,以及 String 每個數位專案的物件。 如果您的應用程式需要最佳效能,或如果管理記憶體配置在您的應用程式中很重要,請考慮使用 IndexOfIndexOfAny 方法,並選擇性地 Compare 在字串內尋找子字串串。

如果您要在分隔符上分割字串,請使用 IndexOfIndexOfAny 方法來找出字元串中的分隔符。 如果您要在分隔符字串上分割字串,請使用 IndexOfIndexOfAny 方法來找出分隔符字串的第一個字元。 Compare然後使用 方法來判斷該第一個字元後面的字元是否等於分隔符字串的其餘字元。

此外,如果使用相同的字元集來分割多個 Split 方法呼叫中的字串,請考慮建立單一陣列,並在每個方法呼叫中參考它。 這可大幅減少每個方法呼叫的額外負荷。

給呼叫者的注意事項

在 .NET Framework 3.5 和較舊版本中,如果Split(Char[])方法傳遞separator了 ,null或不包含任何字元,則方法會使用稍微不同的空格符集來分割字串,而不是Trim(Char[])方法修剪字元串。 從 .NET Framework 4 開始,這兩種方法都會使用相同的 Unicode 空格符集。

適用於

Split(Char, Int32, StringSplitOptions)

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs

根據指定的分隔字元和選擇性選項,將一個字串分割成最多數量的子字串。 根據提供的字元分隔符號,將一個字串分割成最多數量的子字串,並選擇性省略結果中的空白子字串。

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

參數

separator
Char

此執行個體中分隔子字串的字元。

count
Int32

陣列中預期的元素數目上限。

options
StringSplitOptions

列舉值的位元組合,可指定是否要修剪子字串並包含空的子字串。

傳回

String[]

陣列,最多包含 count 個來自此執行個體的子字串,以 separator 分隔。

備註

如果字串已經分割 count - 1 次,但尚未到達字串結尾,則傳回數位中的最後一個字串將包含這個實例的剩餘尾端子字串,不會變更。

適用於

Split(Char[], Int32, StringSplitOptions)

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs

根據指定的分隔字元和選擇性選項,將一個字串分割成最多的子字串。

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

參數

separator
Char[]

在此字串中分隔數個子字串的字元陣列、不包含分隔符號的空陣列、或 null

count
Int32

要傳回的子字串之最大數目。

options
StringSplitOptions

列舉值的位元組合,可指定是否要修剪子字串並包含空的子字串。

傳回

String[]

陣列,包含這個字串的子字串,以 separator 中的一或多個字元分隔。 如需詳細資訊,請參閱<備註>一節。

屬性

例外狀況

count 為負。

options 不是其中一個 StringSplitOptions 值。

範例

下列範例會 StringSplitOptions 使用 列舉來包含或排除 方法所產生的 Split 子字串。

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

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

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

/*
This example produces the following results:

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

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

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

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

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

*/
// This example demonstrates the String.Split() methods that use
// the StringSplitOptions enumeration.
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(String[], Int32, StringSplitOptions)char[] separator 下列範例示範數種方式,明確識別此多載。

string phrase = "The quick  brown fox";

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

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

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

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

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

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

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

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

count如果參數為零,或options參數為 RemoveEmptyEntries ,且此實例的長度為零,則會傳回空陣列。

的每個元素 separator 都會定義個別的分隔符。 options如果 參數是 None,而且兩個分隔符是相鄰的,或在這個實例的開頭或結尾找到分隔符,則對應的陣列元素會Empty包含 。

如果這個實例中有超過count子字串,則會在傳回值的第一個減 1 個元素中傳回第一countcount個減去 1 個子字串,而這個實例中的其餘字元則會在傳回值的最後一個元素中傳回。

如果 count 大於子字串的數目,則會傳回可用的子字串,而且不會擲回例外狀況。

效能考量

方法 Split 會為傳回的陣列物件配置記憶體,以及 String 每個數位專案的物件。 如果您的應用程式需要最佳效能,或如果管理記憶體配置在您的應用程式中很重要,請考慮使用 IndexOfIndexOfAny 方法,並選擇性地 Compare 在字串內尋找子字串串。

如果您要在分隔符上分割字串,請使用 IndexOfIndexOfAny 方法來找出字元串中的分隔符。 如果您要在分隔符字串上分割字串,請使用 IndexOfIndexOfAny 方法來找出分隔符字串的第一個字元。 Compare然後使用 方法來判斷該第一個字元後面的字元是否等於分隔符字串的其餘字元。

此外,如果使用相同的字元集來分割多個 Split 方法呼叫中的字串,請考慮建立單一陣列,並在每個方法呼叫中參考它。 這可大幅減少每個方法呼叫的額外負荷。

給呼叫者的注意事項

在 .NET Framework 3.5 和較舊版本中,如果Split(Char[])方法傳遞separator了 ,null或不包含任何字元,則方法會使用稍微不同的空格符集來分割字串,而不是Trim(Char[])方法修剪字元串。 從 .NET Framework 4 開始,這兩種方法都會使用相同的 Unicode 空格符集。

適用於

Split(String, Int32, StringSplitOptions)

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs

根據指定的分隔字串和選擇性選項,將一個字串分割成最多的子字串。

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

參數

separator
String

此執行個體中分隔子字串的字串。

count
Int32

陣列中預期的元素數目上限。

options
StringSplitOptions

列舉值的位元組合,可指定是否要修剪子字串並包含空的子字串。

傳回

String[]

陣列,最多包含 count 個來自此執行個體的子字串,以 separator 分隔。

備註

如果字串已經分割 count - 1 次,但尚未到達字串結尾,則傳回數位中的最後一個字串將包含這個實例的剩餘尾端子字串,不會變更。

適用於

Split(String[], Int32, StringSplitOptions)

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs

根據指定的分隔字串和選擇性選項,將一個字串分割成最多的子字串。

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

參數

separator
String[]

在此字串中分隔子字串的字串、不包含分隔符號的空陣列、或 null

count
Int32

要傳回的子字串之最大數目。

options
StringSplitOptions

列舉值的位元組合,可指定是否要修剪子字串並包含空的子字串。

傳回

String[]

陣列,其項目包含了這個字串中由 separator 內的一或多個字串所分隔的子字串。 如需詳細資訊,請參閱<備註>一節。

屬性

例外狀況

count 為負。

options 不是其中一個 StringSplitOptions 值。

範例

下列範例會 StringSplitOptions 使用 列舉來包含或排除 方法所產生的 Split 子字串。

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

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

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

/*
This example produces the following results:

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

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

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

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

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

*/
// This example demonstrates the String.Split() methods that use
// the StringSplitOptions enumeration.
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子字串,則會在傳回值的第一個減 1 個元素中傳回第一countcount個減去 1 個子字串,而這個實例中的其餘字元則會在傳回值的最後一個元素中傳回。

如果 count 大於子字串的數目,則會傳回可用的子字串,而且不會擲回例外狀況。

分隔符陣列

如果中的任何 separator 專案包含多個字元,則會將整個子字串視為分隔符。 例如,如果 中的 separator 其中一個元素是 “10”,則嘗試分割字串 “This10is10a10string”。“ 會傳回這個四個元素陣列: { ”This“、”is“、”a“、”string.“ }。

比較詳細數據

方法 Split 會擷取這個字串中的子字串,這些子字串是以 參數中的 separator 一或多個字串分隔,並傳回這些子字串做為陣列的專案。

方法會 Split 藉由使用區分大小寫的序數排序規則來執行比較來尋找分隔符。 如需字組、字串和序數排序的詳細資訊,請參閱 System.Globalization.CompareOptions 列舉。

方法Split會忽略其值為 null 或空字串 (“”“) 的任何專案separator

若要避免在 中的 separator 字串具有通用字元時模棱兩可的結果, Split 方法會從 實例值的開頭到結尾,並比對 實例中 separator 第一個元素等於 實例中的分隔符。 實例中遇到子字串的順序優先於 中的 separator項目順序。

例如,假設實例的值是 “abcdef”。 如果 中的 separator 第一個專案是 「ef」,而第二個元素是 “bcde”,則分割作業的結果會是 “a” 和 “f”。 這是因為遇到實例 「bcde」 中的子字串,並在遇到子字串 「f」 之前比對 中的 separator 專案。

不過,如果的第一個專案是 “bcd”,而第二個元素 separator 是 “bc”,分割作業的結果會是 “a” 和 “ef”。 這是因為 「bcd」 是 中符合 實例中 separator 分隔符的第一個分隔符。 如果分隔符的順序反轉,因此第一個專案是 “bc”,而第二個元素是 “bcd”,則結果會是 “a” 和 “def”。

效能考量

方法 Split 會為傳回的陣列物件配置記憶體,以及 String 每個數位專案的物件。 如果您的應用程式需要最佳效能,或如果管理記憶體配置在您的應用程式中很重要,請考慮使用 IndexOfIndexOfAny 方法,並選擇性地 Compare 在字串內尋找子字串串。

如果您要在分隔符上分割字串,請使用 IndexOfIndexOfAny 方法來找出字元串中的分隔符。 如果您要在分隔符字串上分割字串,請使用 IndexOfIndexOfAny 方法來找出分隔符字串的第一個字元。 Compare然後使用 方法來判斷該第一個字元後面的字元是否等於分隔符字串的其餘字元。

此外,如果使用相同的字元集來分割多個 Split 方法呼叫中的字串,請考慮建立單一陣列,並在每個方法呼叫中參考它。 這可大幅減少每個方法呼叫的額外負荷。

給呼叫者的注意事項

在 .NET Framework 3.5 和較舊版本中,如果Split(Char[])方法傳遞separator的 是 null 或 不包含任何字元,則方法會使用稍有不同的空格符集來分割字串,而不是Trim(Char[])方法修剪字元串。 從 .NET Framework 4 開始,這兩種方法都會使用相同的 Unicode 空格符集。

適用於