String.Split 方法
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
傳回字串數位,其中包含這個實例中由指定字串或 Unicode 字元陣列的專案分隔的子字串。
多載
Split(String, Int32, StringSplitOptions) |
根據指定的分隔字串,將字串分割成最大子字串數目,並選擇性地將字串分割成最大數目。 |
Split(Char[], Int32, StringSplitOptions) |
根據指定的分隔字元和選擇性選項,將字串分割成最大子字串數目。 |
Split(Char, Int32, StringSplitOptions) |
根據指定的分隔字元,將字串分割成子字串數目上限,並選擇性地分割成子字串。 根據提供的字元分隔符,將字串分割成最大子字串數目,選擇性地省略結果中的空白子字串。 |
Split(String[], StringSplitOptions) |
根據指定的分隔字串,將字串分割成子字串串,並選擇性地將字串分割成子字串。 |
Split(String, StringSplitOptions) |
將字串分割成以提供的字串分隔符為基礎的子字串。 |
Split(Char[]) |
根據指定的分隔字元,將字串分割成子字串。 |
Split(Char[], Int32) |
根據指定的分隔字元,將字串分割成最大子字串數目。 |
Split(Char, StringSplitOptions) |
根據指定的分隔字元,將字串分割成子字串,並選擇性地將字串分割成子字串。 |
Split(ReadOnlySpan<Char>) |
根據指定的分隔字元,將字串分割成子字串。 |
Split(String[], Int32, StringSplitOptions) |
根據指定的分隔字串和選擇性選項,將字串分割成子字串數目上限。 |
Split(Char[], StringSplitOptions) |
根據指定的分隔字元和選項,將字串分割成子字串。 |
備註
Split 用來將分隔字串分成子字串。 您可以使用字元陣列或字串數組來指定零個或多個分隔字元或字串。 如果未指定任何分隔字元,字串會分割成空格符。
Split 方法的多載可讓您限制 方法傳回的子字串數目(Split(Char[], Int32) 方法),以指定是否要在結果中包含空字串串和/或修剪子字元串(Split(Char[], StringSplitOptions) 和 Split(String[], StringSplitOptions) 方法),或同時執行 (Split(Char[], Int32, StringSplitOptions) 和 Split(String[], Int32, StringSplitOptions) 方法)。
提示
Split 方法不一定是將分隔字串分成子字串的最佳方式。 如果您不想要擷取分隔字串的所有子字串,或如果您想要根據模式剖析字串,而不是使用一組分隔符,請考慮使用正則表達式,或結合其中一個搜尋方法,以 Substring 方法傳回字元的索引。 如需詳細資訊,請參閱 從字串擷取子字串。
例
下列範例顯示三個不同的 String.Split()
多載。 第一個範例會呼叫 Split(Char[]) 多載,並傳入單一分隔符。
string s = "You win some. You lose some.";
string[] subs = s.Split(' ');
foreach (var sub in subs)
{
Console.WriteLine($"Substring: {sub}");
}
// This example produces the following output:
//
// Substring: You
// Substring: win
// Substring: some.
// Substring: You
// Substring: lose
// Substring: some.
let s = "You win some. You lose some."
let subs = s.Split ' '
for sub in subs do
printfn $"Substring: {sub}"
// This example produces the following output:
//
// Substring: You
// Substring: win
// Substring: some.
// Substring: You
// Substring: lose
// Substring: some.
Dim s As String = "You win some. You lose some."
Dim subs As String() = s.Split()
For Each substring As String In subs
Console.WriteLine($"Substring: {substring}")
Next
' This example produces the following output:
'
' Substring: You
' Substring: win
' Substring: some.
' Substring: You
' Substring: lose
' Substring: some.
如您所見,句號字元 (.
) 包含在兩個子字串中。 如果您想要排除句點字元,您可以將句點字元新增為額外的分隔字元。 下一個範例示範如何執行這項操作。
string s = "You win some. You lose some.";
string[] subs = s.Split(' ', '.');
foreach (var sub in subs)
{
Console.WriteLine($"Substring: {sub}");
}
// This example produces the following output:
//
// Substring: You
// Substring: win
// Substring: some
// Substring:
// Substring: You
// Substring: lose
// Substring: some
// Substring:
let s = "You win some. You lose some."
let subs = s.Split(' ', '.')
for sub in subs do
printfn $"Substring: {sub}"
// This example produces the following output:
//
// Substring: You
// Substring: win
// Substring: some
// Substring:
// Substring: You
// Substring: lose
// Substring: some
// Substring:
Dim s As String = "You win some. You lose some."
Dim subs As String() = s.Split(" "c, "."c)
For Each substring As String In subs
Console.WriteLine($"Substring: {substring}")
Next
' This example produces the following output:
'
' Substring: You
' Substring: win
' Substring: some
' Substring:
' Substring: You
' Substring: lose
' Substring: some
' Substring:
期間會從子字串中消失,但現在已包含兩個額外的空白子字串。 這些空子字串代表單字與後面句號之間的子字串。 若要省略結果陣列中的空白子字串,您可以呼叫 Split(Char[], StringSplitOptions) 多載,併為 options
參數指定 StringSplitOptions.RemoveEmptyEntries。
string s = "You win some. You lose some.";
char[] separators = new char[] { ' ', '.' };
string[] subs = s.Split(separators, StringSplitOptions.RemoveEmptyEntries);
foreach (var sub in subs)
{
Console.WriteLine($"Substring: {sub}");
}
// This example produces the following output:
//
// Substring: You
// Substring: win
// Substring: some
// Substring: You
// Substring: lose
// Substring: some
let s = "You win some. You lose some."
let separators = [| ' '; '.' |]
let subs = s.Split(separators, StringSplitOptions.RemoveEmptyEntries)
for sub in subs do
printfn $"Substring: {sub}"
// This example produces the following output:
//
// Substring: You
// Substring: win
// Substring: some
// Substring: You
// Substring: lose
// Substring: some
Dim s As String = "You win some. You lose some."
Dim separators As Char() = New Char() {" "c, "."c}
Dim subs As String() = s.Split(separators, StringSplitOptions.RemoveEmptyEntries)
For Each substring As String In subs
Console.WriteLine($"Substring: {substring}")
Next
' This example produces the following output:
'
' Substring: You
' Substring: win
' Substring: some
' Substring: You
' Substring: lose
' Substring: some
String.Split()
個別多載的區段包含進一步的範例。
Split(String, Int32, StringSplitOptions)
根據指定的分隔字串,將字串分割成最大子字串數目,並選擇性地將字串分割成最大數目。
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
列舉值的位元組合,指定是否要修剪子字串並包含空子字串。
傳回
陣列,最多包含由 separator
分隔之這個實例的 count
子字串。
備註
如果字串已經分割 count
- 1 次,但尚未到達字串的結尾,則傳回陣列中的最後一個字串將包含這個實例的剩餘尾端子字串,未變更。
適用於
Split(Char[], Int32, StringSplitOptions)
根據指定的分隔字元和選擇性選項,將字串分割成最大子字串數目。
public:
cli::array <System::String ^> ^ Split(cli::array <char> ^ separator, int count, StringSplitOptions options);
public string[] Split (char[] separator, int count, StringSplitOptions options);
public string[] Split (char[]? separator, int count, StringSplitOptions options);
[System.Runtime.InteropServices.ComVisible(false)]
public string[] Split (char[] separator, int count, StringSplitOptions options);
member this.Split : char[] * int * StringSplitOptions -> string[]
[<System.Runtime.InteropServices.ComVisible(false)>]
member this.Split : char[] * int * StringSplitOptions -> string[]
Public Function Split (separator As Char(), count As Integer, options As StringSplitOptions) As String()
參數
- separator
- Char[]
此字串中分隔子字串的字元陣列、不含分隔符的空陣列,或 null
。
- count
- Int32
要傳回的子字串數目上限。
- options
- StringSplitOptions
列舉值的位元組合,指定是否要修剪子字串並包含空子字串。
傳回
陣列,包含此字串中的子字串,並以 separator
中的一或多個字元分隔。 如需詳細資訊,請參閱一節。
- 屬性
例外狀況
count
為負數。
options
不是其中一個 StringSplitOptions 值。
範例
下列範例會使用 StringSplitOptions 列舉來包含或排除 Split 方法所產生的子字串。
// This example demonstrates the String.Split(Char[], Boolean) and
// String.Split(Char[], Int32, Boolean) methods
using namespace System;
void Show( array<String^>^entries )
{
Console::WriteLine( "The return value contains these {0} elements:", entries->Length );
System::Collections::IEnumerator^ myEnum = entries->GetEnumerator();
while ( myEnum->MoveNext() )
{
String^ entry = safe_cast<String^>(myEnum->Current);
Console::Write( "<{0}>", entry );
}
Console::Write( "{0}{0}", Environment::NewLine );
}
int main()
{
String^ s = ",one,,,two,,,,,three,,";
array<Char>^sep = gcnew array<Char>{
','
};
array<String^>^result;
//
Console::WriteLine( "The original string is \"{0}\".", s );
Console::WriteLine( "The separation character is '{0}'.", sep[ 0 ] );
Console::WriteLine();
//
Console::WriteLine( "Split the string and return all elements:" );
result = s->Split( sep, StringSplitOptions::None );
Show( result );
//
Console::WriteLine( "Split the string and return all non-empty elements:" );
result = s->Split( sep, StringSplitOptions::RemoveEmptyEntries );
Show( result );
//
Console::WriteLine( "Split the string and return 2 elements:" );
result = s->Split( sep, 2, StringSplitOptions::None );
Show( result );
//
Console::WriteLine( "Split the string and return 2 non-empty elements:" );
result = s->Split( sep, 2, StringSplitOptions::RemoveEmptyEntries );
Show( result );
}
/*
This example produces the following results:
The original string is ",one,,,two,,,,,three,,".
The separation character is ','.
Split the string and return all elements:
The return value contains these 12 elements:
<><one><><><two><><><><><three><><>
Split the string and return all non-empty elements:
The return value contains these 3 elements:
<one><two><three>
Split the string and return 2 elements:
The return value contains these 2 elements:
<><one,,,two,,,,,three,,>
Split the string and return 2 non-empty elements:
The return value contains these 2 elements:
<one><,,two,,,,,three,,>
*/
// This example demonstrates the String.Split() methods that use
// the StringSplitOptions enumeration.
// Example 1: Split a string delimited by characters
Console.WriteLine("1) Split a string delimited by characters:\n");
string s1 = ",ONE,, TWO,, , THREE,,";
char[] charSeparators = new char[] { ',' };
string[] result;
Console.WriteLine($"The original string is: \"{s1}\".");
Console.WriteLine($"The delimiter character is: '{charSeparators[0]}'.\n");
// Split the string and return all elements
Console.WriteLine("1a) Return all elements:");
result = s1.Split(charSeparators, StringSplitOptions.None);
Show(result);
// Split the string and return all elements with whitespace trimmed
Console.WriteLine("1b) Return all elements with whitespace trimmed:");
result = s1.Split(charSeparators, StringSplitOptions.TrimEntries);
Show(result);
// Split the string and return all non-empty elements
Console.WriteLine("1c) Return all non-empty elements:");
result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// Split the string and return all non-whitespace elements with whitespace trimmed
Console.WriteLine("1d) Return all non-whitespace elements with whitespace trimmed:");
result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
Show(result);
// Split the string into only two elements, keeping the remainder in the last match
Console.WriteLine("1e) Split into only two elements:");
result = s1.Split(charSeparators, 2, StringSplitOptions.None);
Show(result);
// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("1f) Split into only two elements with whitespace trimmed:");
result = s1.Split(charSeparators, 2, StringSplitOptions.TrimEntries);
Show(result);
// Split the string into only two non-empty elements, keeping the remainder in the last match
Console.WriteLine("1g) Split into only two non-empty elements:");
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("1h) Split into only two non-whitespace elements with whitespace trimmed:");
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
Show(result);
// Example 2: Split a string delimited by another string
Console.WriteLine("2) Split a string delimited by another string:\n");
string s2 = "[stop]" +
"ONE[stop] [stop]" +
"TWO [stop][stop] [stop]" +
"THREE[stop][stop] ";
string[] stringSeparators = new string[] { "[stop]" };
Console.WriteLine($"The original string is: \"{s2}\".");
Console.WriteLine($"The delimiter string is: \"{stringSeparators[0]}\".\n");
// Split the string and return all elements
Console.WriteLine("2a) Return all elements:");
result = s2.Split(stringSeparators, StringSplitOptions.None);
Show(result);
// Split the string and return all elements with whitespace trimmed
Console.WriteLine("2b) Return all elements with whitespace trimmed:");
result = s2.Split(stringSeparators, StringSplitOptions.TrimEntries);
Show(result);
// Split the string and return all non-empty elements
Console.WriteLine("2c) Return all non-empty elements:");
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// Split the string and return all non-whitespace elements with whitespace trimmed
Console.WriteLine("2d) Return all non-whitespace elements with whitespace trimmed:");
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
Show(result);
// Split the string into only two elements, keeping the remainder in the last match
Console.WriteLine("2e) Split into only two elements:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.None);
Show(result);
// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("2f) Split into only two elements with whitespace trimmed:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.TrimEntries);
Show(result);
// Split the string into only two non-empty elements, keeping the remainder in the last match
Console.WriteLine("2g) Split into only two non-empty elements:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("2h) Split into only two non-whitespace elements with whitespace trimmed:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
Show(result);
// Display the array of separated strings using a local function
void Show(string[] entries)
{
Console.WriteLine($"The return value contains these {entries.Length} elements:");
foreach (string entry in entries)
{
Console.Write($"<{entry}>");
}
Console.Write("\n\n");
}
/*
This example produces the following results:
1) Split a string delimited by characters:
The original string is: ",ONE,, TWO,, , THREE,,".
The delimiter character is: ','.
1a) Return all elements:
The return value contains these 9 elements:
<><ONE><>< TWO><>< >< THREE><><>
1b) Return all elements with whitespace trimmed:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>
1c) Return all non-empty elements:
The return value contains these 4 elements:
<ONE>< TWO>< >< THREE>
1d) Return all non-whitespace elements with whitespace trimmed:
The return value contains these 3 elements:
<ONE><TWO><THREE>
1e) Split into only two elements:
The return value contains these 2 elements:
<><ONE,, TWO,, , THREE,,>
1f) Split into only two elements with whitespace trimmed:
The return value contains these 2 elements:
<><ONE,, TWO,, , THREE,,>
1g) Split into only two non-empty elements:
The return value contains these 2 elements:
<ONE>< TWO,, , THREE,,>
1h) Split into only two non-whitespace elements with whitespace trimmed:
The return value contains these 2 elements:
<ONE><TWO,, , THREE,,>
2) Split a string delimited by another string:
The original string is: "[stop]ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] ".
The delimiter string is: "[stop]".
2a) Return all elements:
The return value contains these 9 elements:
<><ONE>< ><TWO ><>< ><THREE><>< >
2b) Return all elements with whitespace trimmed:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>
2c) Return all non-empty elements:
The return value contains these 6 elements:
<ONE>< ><TWO >< ><THREE>< >
2d) Return all non-whitespace elements with whitespace trimmed:
The return value contains these 3 elements:
<ONE><TWO><THREE>
2e) Split into only two elements:
The return value contains these 2 elements:
<><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] >
2f) Split into only two elements with whitespace trimmed:
The return value contains these 2 elements:
<><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop]>
2g) Split into only two non-empty elements:
The return value contains these 2 elements:
<ONE>< [stop]TWO [stop][stop] [stop]THREE[stop][stop] >
2h) Split into only two non-whitespace elements with whitespace trimmed:
The return value contains these 2 elements:
<ONE><TWO [stop][stop] [stop]THREE[stop][stop]>
*/
// This example demonstrates the String.Split() methods that use
// the StringSplitOptions enumeration.
// Display the array of separated strings using a local function
let show (entries: string[]) =
printfn $"The return value contains these {entries.Length} elements:"
for entry in entries do
printf $"<{entry}>"
printf "\n\n"
// Example 1: Split a string delimited by characters
printfn "1) Split a string delimited by characters:\n"
let s1 = ",ONE,, TWO,, , THREE,,"
let charSeparators = [| ',' |]
printfn $"The original string is: \"{s1}\"."
printfn $"The delimiter character is: '{charSeparators[0]}'.\n"
// Split the string and return all elements
printfn "1a) Return all elements:"
let result = s1.Split(charSeparators, StringSplitOptions.None)
show result
// Split the string and return all elements with whitespace trimmed
printfn "1b) Return all elements with whitespace trimmed:"
let result = s1.Split(charSeparators, StringSplitOptions.TrimEntries)
show result
// Split the string and return all non-empty elements
printfn "1c) Return all non-empty elements:"
let result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries)
show result
// Split the string and return all non-whitespace elements with whitespace trimmed
printfn "1d) Return all non-whitespace elements with whitespace trimmed:"
let result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)
show result
// Split the string into only two elements, keeping the remainder in the last match
printfn "1e) Split into only two elements:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.None)
show result
// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
printfn "1f) Split into only two elements with whitespace trimmed:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.TrimEntries)
show result
// Split the string into only two non-empty elements, keeping the remainder in the last match
printfn "1g) Split into only two non-empty elements:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
show result
// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
printfn "1h) Split into only two non-whitespace elements with whitespace trimmed:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)
show result
// Example 2: Split a string delimited by another string
printfn "2) Split a string delimited by another string:\n"
let s2 = "[stop]" +
"ONE[stop] [stop]" +
"TWO [stop][stop] [stop]" +
"THREE[stop][stop] "
let stringSeparators = [| "[stop]" |]
printfn $"The original string is: \"{s2}\"."
printfn $"The delimiter string is: \"{stringSeparators[0]}\".\n"
// Split the string and return all elements
printfn "2a) Return all elements:"
let result = s2.Split(stringSeparators, StringSplitOptions.None)
show result
// Split the string and return all elements with whitespace trimmed
printfn "2b) Return all elements with whitespace trimmed:"
let result = s2.Split(stringSeparators, StringSplitOptions.TrimEntries)
show result
// Split the string and return all non-empty elements
printfn "2c) Return all non-empty elements:"
let result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)
show result
// Split the string and return all non-whitespace elements with whitespace trimmed
printfn "2d) Return all non-whitespace elements with whitespace trimmed:"
let result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)
show result
// Split the string into only two elements, keeping the remainder in the last match
printfn "2e) Split into only two elements:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.None)
show result
// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
printfn "2f) Split into only two elements with whitespace trimmed:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.TrimEntries)
show result
// Split the string into only two non-empty elements, keeping the remainder in the last match
printfn "2g) Split into only two non-empty elements:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
show result
// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
printfn "2h) Split into only two non-whitespace elements with whitespace trimmed:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)
show result
(*
This example produces the following results:
1) Split a string delimited by characters:
The original string is: ",ONE,, TWO,, , THREE,,".
The delimiter character is: ','.
1a) Return all elements:
The return value contains these 9 elements:
<><ONE><>< TWO><>< >< THREE><><>
1b) Return all elements with whitespace trimmed:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>
1c) Return all non-empty elements:
The return value contains these 4 elements:
<ONE>< TWO>< >< THREE>
1d) Return all non-whitespace elements with whitespace trimmed:
The return value contains these 3 elements:
<ONE><TWO><THREE>
1e) Split into only two elements:
The return value contains these 2 elements:
<><ONE,, TWO,, , THREE,,>
1f) Split into only two elements with whitespace trimmed:
The return value contains these 2 elements:
<><ONE,, TWO,, , THREE,,>
1g) Split into only two non-empty elements:
The return value contains these 2 elements:
<ONE>< TWO,, , THREE,,>
1h) Split into only two non-whitespace elements with whitespace trimmed:
The return value contains these 2 elements:
<ONE><TWO,, , THREE,,>
2) Split a string delimited by another string:
The original string is: "[stop]ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] ".
The delimiter string is: "[stop]".
2a) Return all elements:
The return value contains these 9 elements:
<><ONE>< ><TWO ><>< ><THREE><>< >
2b) Return all elements with whitespace trimmed:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>
2c) Return all non-empty elements:
The return value contains these 6 elements:
<ONE>< ><TWO >< ><THREE>< >
2d) Return all non-whitespace elements with whitespace trimmed:
The return value contains these 3 elements:
<ONE><TWO><THREE>
2e) Split into only two elements:
The return value contains these 2 elements:
<><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] >
2f) Split into only two elements with whitespace trimmed:
The return value contains these 2 elements:
<><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop]>
2g) Split into only two non-empty elements:
The return value contains these 2 elements:
<ONE>< [stop]TWO [stop][stop] [stop]THREE[stop][stop] >
2h) Split into only two non-whitespace elements with whitespace trimmed:
The return value contains these 2 elements:
<ONE><TWO [stop][stop] [stop]THREE[stop][stop]>
*)
Public Shared Sub StringSplitOptionsExamples()
' This example demonstrates the String.Split() methods that use
' the StringSplitOptions enumeration.
' Example 1: Split a string delimited by characters
Console.WriteLine("1) Split a string delimited by characters:" & vbCrLf)
Dim s1 As String = ",ONE,, TWO,, , THREE,,"
Dim charSeparators() As Char = {","c}
Dim result() As String
Console.WriteLine("The original string is: ""{0}"".", s1)
Console.WriteLine("The delimiter character is: '{0}'." & vbCrLf, charSeparators(0))
' Split the string and return all elements
Console.WriteLine("1a) Return all elements:")
result = s1.Split(charSeparators, StringSplitOptions.None)
Show(result)
' Split the string and return all elements with whitespace trimmed
Console.WriteLine("1b) Return all elements with whitespace trimmed:")
result = s1.Split(charSeparators, StringSplitOptions.TrimEntries)
Show(result)
' Split the string and return all non-empty elements
Console.WriteLine("1c) Return all non-empty elements:")
result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries)
Show(result)
' Split the string and return all non-whitespace elements with whitespace trimmed
Console.WriteLine("1d) Return all non-whitespace elements with whitespace trimmed:")
result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries)
Show(result)
' Split the string into only two elements, keeping the remainder in the last match
Console.WriteLine("1e) Split into only two elements:")
result = s1.Split(charSeparators, 2, StringSplitOptions.None)
Show(result)
' Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("1f) Split into only two elements with whitespace trimmed:")
result = s1.Split(charSeparators, 2, StringSplitOptions.TrimEntries)
Show(result)
' Split the string into only two non-empty elements, keeping the remainder in the last match
Console.WriteLine("1g) Split into only two non-empty elements:")
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
Show(result)
' Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("1h) Split into only two non-whitespace elements with whitespace trimmed:")
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries)
Show(result)
' Example 2: Split a string delimited by another string
Console.WriteLine("2) Split a string delimited by another string:" & vbCrLf)
Dim s2 As String = "[stop]" +
"ONE[stop] [stop]" +
"TWO [stop][stop] [stop]" +
"THREE[stop][stop] "
Dim stringSeparators() As String = {"[stop]"}
Console.WriteLine("The original string is: ""{0}"".", s2)
Console.WriteLine("The delimiter string is: ""{0}""." & vbCrLf, stringSeparators(0))
' Split the string and return all elements
Console.WriteLine("2a) Return all elements:")
result = s2.Split(stringSeparators, StringSplitOptions.None)
Show(result)
' Split the string and return all elements with whitespace trimmed
Console.WriteLine("2b) Return all elements with whitespace trimmed:")
result = s2.Split(stringSeparators, StringSplitOptions.TrimEntries)
Show(result)
' Split the string and return all non-empty elements
Console.WriteLine("2c) Return all non-empty elements:")
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)
Show(result)
' Split the string and return all non-whitespace elements with whitespace trimmed
Console.WriteLine("2d) Return all non-whitespace elements with whitespace trimmed:")
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries)
Show(result)
' Split the string into only two elements, keeping the remainder in the last match
Console.WriteLine("2e) Split into only two elements:")
result = s2.Split(stringSeparators, 2, StringSplitOptions.None)
Show(result)
' Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("2f) Split into only two elements with whitespace trimmed:")
result = s2.Split(stringSeparators, 2, StringSplitOptions.TrimEntries)
Show(result)
' Split the string into only two non-empty elements, keeping the remainder in the last match
Console.WriteLine("2g) Split into only two non-empty elements:")
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
Show(result)
' Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("2h) Split into only two non-whitespace elements with whitespace trimmed:")
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries)
Show(result)
End Sub
' Display the array of separated strings.
Public Shared Sub Show(ByVal entries() As String)
Console.WriteLine("The return value contains these {0} elements:", entries.Length)
Dim entry As String
For Each entry In entries
Console.Write("<{0}>", entry)
Next entry
Console.Write(vbCrLf & vbCrLf)
End Sub
'This example produces the following results:
'
' 1) Split a string delimited by characters:
'
' The original string is: ",ONE,, TWO,, , THREE,,".
' The delimiter character is: ','.
'
' 1a) Return all elements:
' The return value contains these 9 elements:
' <><ONE><>< TWO><>< >< THREE><><>
'
' 1b) Return all elements with whitespace trimmed:
' The return value contains these 9 elements:
' <><ONE><><TWO><><><THREE><><>
'
' 1c) Return all non-empty elements:
' The return value contains these 4 elements:
' <ONE>< TWO>< >< THREE>
'
' 1d) Return all non-whitespace elements with whitespace trimmed:
' The return value contains these 3 elements:
' <ONE><TWO><THREE>
'
' 1e) Split into only two elements:
' The return value contains these 2 elements:
' <><ONE,, TWO,, , THREE,,>
'
' 1f) Split into only two elements with whitespace trimmed:
' The return value contains these 2 elements:
' <><ONE,, TWO,, , THREE,,>
'
' 1g) Split into only two non-empty elements:
' The return value contains these 2 elements:
' <ONE>< TWO,, , THREE,,>
'
' 1h) Split into only two non-whitespace elements with whitespace trimmed:
' The return value contains these 2 elements:
' <ONE><TWO,, , THREE,,>
'
' 2) Split a string delimited by another string:
'
' The original string is: "[stop]ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] ".
' The delimiter string is: "[stop]".
'
' 2a) Return all elements:
' The return value contains these 9 elements:
' <><ONE>< ><TWO ><>< ><THREE><>< >
'
' 2b) Return all elements with whitespace trimmed:
' The return value contains these 9 elements:
' <><ONE><><TWO><><><THREE><><>
'
' 2c) Return all non-empty elements:
' The return value contains these 6 elements:
' <ONE>< ><TWO >< ><THREE>< >
'
' 2d) Return all non-whitespace elements with whitespace trimmed:
' The return value contains these 3 elements:
' <ONE><TWO><THREE>
'
' 2e) Split into only two elements:
' The return value contains these 2 elements:
' <><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] >
'
' 2f) Split into only two elements with whitespace trimmed:
' The return value contains these 2 elements:
' <><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop]>
'
' 2g) Split into only two non-empty elements:
' The return value contains these 2 elements:
' <ONE>< [stop]TWO [stop][stop] [stop]THREE[stop][stop] >
'
' 2h) Split into only two non-whitespace elements with whitespace trimmed:
' The return value contains these 2 elements:
' <ONE><TWO [stop][stop] [stop]THREE[stop][stop]>
'
備註
傳回數位元素中不包含分隔符。
如果這個實例不包含 separator
中的任何字元,或 count
參數為 1,則傳回的陣列是由包含這個實例的單一元素所組成。
如果 separator
參數是 null
或不包含任何字元,則空格符會假設為分隔符。 空格符是由 Unicode 標準所定義,Char.IsWhiteSpace 方法會傳回 true
傳遞至該字元。
若要傳遞 char[] separator
參數的 null
,您必須指出 null
的類型,以釐清呼叫與其他多載,例如 Split(String[], Int32, StringSplitOptions)。 下列範例示範數種方式來明確識別此多載。
string phrase = "The quick brown fox";
_ = phrase.Split(default(char[]), 3, StringSplitOptions.RemoveEmptyEntries);
_ = phrase.Split((char[]?)null, 3, StringSplitOptions.RemoveEmptyEntries);
_ = phrase.Split(null as char[], 3, StringSplitOptions.RemoveEmptyEntries);
let phrase = "The quick brown fox"
phrase.Split(Unchecked.defaultof<char[]>, 3, StringSplitOptions.RemoveEmptyEntries) |> ignore
phrase.Split(null :> char[], 3, StringSplitOptions.RemoveEmptyEntries) |> ignore
phrase.Split((null: char[]), 3, StringSplitOptions.RemoveEmptyEntries) |> ignore
Dim phrase As String = "The quick brown fox"
Dim words() As String
words = phrase.Split(TryCast(Nothing, Char()), 3,
StringSplitOptions.RemoveEmptyEntries)
words = phrase.Split(New Char() {}, 3,
StringSplitOptions.RemoveEmptyEntries)
如果 count
參數為零,或 options
參數 RemoveEmptyEntries 且這個實例的長度為零,則會傳回空陣列。
separator
的每個元素都會定義個別的分隔符。 如果 options
參數是 None,而且兩個分隔符是相鄰的,或是在這個實例的開頭或結尾找到分隔符,則對應的陣列元素會包含 Empty。
如果這個實例中有超過 count
個子字串,第一個 count
減 1 個子字串會在傳回值的第一個 count
減 1 個元素中傳回,而這個實例中的其餘字元會在傳回值的最後一個元素中傳回。
如果 count
大於子字串的數目,則會傳回可用的子字串,而且不會擲回任何例外狀況。
效能考慮
Split 方法會配置傳回數位物件的記憶體,以及每個數位元素的 String 物件。 如果您的應用程式需要最佳效能,或管理記憶體配置在應用程式中很重要,請考慮使用 IndexOf 或 IndexOfAny 方法,以及選擇性地使用 Compare 方法,在字串中尋找子字串串。
如果您要在分隔字元分割字串,請使用 IndexOf 或 IndexOfAny 方法來找出字串中的分隔字元。 如果您要在分隔符字串分割字串,請使用 IndexOf 或 IndexOfAny 方法來找出分隔符字串的第一個字元。 然後使用 Compare 方法來判斷該第一個字元後面的字元是否等於分隔符字串的其餘字元。
此外,如果使用相同的字元集來分割多個 Split 方法呼叫中的字元串,請考慮在每個方法呼叫中建立單一數位並參考它。 這可大幅減少每個方法呼叫的額外額外負荷。
給呼叫者的注意事項
在 .NET Framework 3.5 和舊版中,如果傳遞 Split(Char[]) 方法的 separator
null
或不包含任何字元,則方法會使用稍微不同的空格符集來分割字符串,而不是 Trim(Char[]) 方法來修剪字串。 從 .NET Framework 4 開始,這兩種方法都會使用相同的 Unicode 空格符集。
適用於
Split(Char, Int32, StringSplitOptions)
根據指定的分隔字元,將字串分割成子字串數目上限,並選擇性地分割成子字串。 根據提供的字元分隔符,將字串分割成最大子字串數目,選擇性地省略結果中的空白子字串。
public string[] Split (char separator, int count, StringSplitOptions options = System.StringSplitOptions.None);
member this.Split : char * int * StringSplitOptions -> string[]
Public Function Split (separator As Char, count As Integer, Optional options As StringSplitOptions = System.StringSplitOptions.None) As String()
參數
- separator
- Char
分隔這個實例中子字串的字元。
- count
- Int32
陣列中預期的元素數目上限。
- options
- StringSplitOptions
列舉值的位元組合,指定是否要修剪子字串並包含空子字串。
傳回
陣列,最多包含由 separator
分隔之這個實例的 count
子字串。
備註
如果字串已經分割 count
- 1 次,但尚未到達字串的結尾,則傳回陣列中的最後一個字串將包含這個實例的剩餘尾端子字串,未變更。
適用於
Split(String[], StringSplitOptions)
根據指定的分隔字串,將字串分割成子字串串,並選擇性地將字串分割成子字串。
public:
cli::array <System::String ^> ^ Split(cli::array <System::String ^> ^ separator, StringSplitOptions options);
public string[] Split (string[] separator, StringSplitOptions options);
public string[] Split (string[]? separator, StringSplitOptions options);
[System.Runtime.InteropServices.ComVisible(false)]
public string[] Split (string[] separator, StringSplitOptions options);
member this.Split : string[] * StringSplitOptions -> string[]
[<System.Runtime.InteropServices.ComVisible(false)>]
member this.Split : string[] * StringSplitOptions -> string[]
Public Function Split (separator As String(), options As StringSplitOptions) As String()
參數
- separator
- String[]
此字串中分隔子字串的字串的字串陣列、不含分隔符的空陣列,或 null
。
- options
- StringSplitOptions
列舉值的位元組合,指定是否要修剪子字串並包含空子字串。
傳回
陣列,其專案包含此字串中的子字串,並以 separator
中的一或多個字串分隔。 如需詳細資訊,請參閱一節。
- 屬性
例外狀況
options
不是其中一個 StringSplitOptions 值。
範例
下列範例說明呼叫字串的 String.Split(String[], StringSplitOptions) 方法所傳回陣列的差異,其 options
參數等於 StringSplitOptions.None 和 StringSplitOptions.RemoveEmptyEntries。
string source = "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]";
string[] stringSeparators = new string[] { "[stop]" };
string[] result;
// Display the original string and delimiter string.
Console.WriteLine($"Splitting the string:\n \"{source}\".");
Console.WriteLine();
Console.WriteLine($"Using the delimiter string:\n \"{stringSeparators[0]}\"");
Console.WriteLine();
// Split a string delimited by another string and return all elements.
result = source.Split(stringSeparators, StringSplitOptions.None);
Console.WriteLine($"Result including all elements ({result.Length} elements):");
Console.Write(" ");
foreach (string s in result)
{
Console.Write("'{0}' ", String.IsNullOrEmpty(s) ? "<>" : s);
}
Console.WriteLine();
Console.WriteLine();
// Split delimited by another string and return all non-empty elements.
result = source.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);
Console.WriteLine($"Result including non-empty elements ({result.Length} elements):");
Console.Write(" ");
foreach (string s in result)
{
Console.Write("'{0}' ", String.IsNullOrEmpty(s) ? "<>" : s);
}
Console.WriteLine();
// The example displays the following output:
// Splitting the string:
// "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".
//
// Using the delimiter string:
// "[stop]"
//
// Result including all elements (9 elements):
// '<>' 'ONE' '<>' 'TWO' '<>' '<>' 'THREE' '<>' '<>'
//
// Result including non-empty elements (3 elements):
// 'ONE' 'TWO' 'THREE'
let source = "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]"
let stringSeparators = [| "[stop]" |]
// Display the original string and delimiter string.
printfn $"Splitting the string:\n \"{source}\".\n"
printfn $"Using the delimiter string:\n \"{stringSeparators[0]}\"\n"
// Split a string delimited by another string and return all elements.
let result = source.Split(stringSeparators, StringSplitOptions.None)
printfn $"Result including all elements ({result.Length} elements):"
printf " "
for s in result do
printf $"""'{if String.IsNullOrEmpty s then "<>" else s}' """
printfn "\n"
// Split delimited by another string and return all non-empty elements.
let result = source.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)
Console.WriteLine($"Result including non-empty elements ({result.Length} elements):")
printf " "
for s in result do
printf $"""'{if String.IsNullOrEmpty s then "<>" else s}' """
printfn ""
// The example displays the following output:
// Splitting the string:
// "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".
//
// Using the delimiter string:
// "[stop]"
//
// let result including all elements (9 elements):
// '<>' 'ONE' '<>' 'TWO' '<>' '<>' 'THREE' '<>' '<>'
//
// let result including non-empty elements (3 elements):
// 'ONE' 'TWO' 'THREE'
Dim source As String = "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]"
Dim stringSeparators() As String = {"[stop]"}
Dim result() As String
' Display the original string and delimiter string.
Console.WriteLine("Splitting the string:{0} '{1}'.", vbCrLf, source)
Console.WriteLine()
Console.WriteLine("Using the delimiter string:{0} '{1}'.",
vbCrLf, stringSeparators(0))
Console.WriteLine()
' Split a string delimited by another string and return all elements.
result = source.Split(stringSeparators, StringSplitOptions.None)
Console.WriteLine("Result including all elements ({0} elements):",
result.Length)
Console.Write(" ")
For Each s As String In result
Console.Write("'{0}' ", IIf(String.IsNullOrEmpty(s), "<>", s))
Next
Console.WriteLine()
Console.WriteLine()
' Split delimited by another string and return all non-empty elements.
result = source.Split(stringSeparators,
StringSplitOptions.RemoveEmptyEntries)
Console.WriteLine("Result including non-empty elements ({0} elements):",
result.Length)
Console.Write(" ")
For Each s As String In result
Console.Write("'{0}' ", IIf(String.IsNullOrEmpty(s), "<>", s))
Next
Console.WriteLine()
' The example displays the following output:
' Splitting the string:
' "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".
'
' Using the delimiter string:
' "[stop]"
'
' Result including all elements (9 elements):
' '<>' 'ONE' '<>' 'TWO' '<>' '<>' 'THREE' '<>' '<>'
'
' Result including non-empty elements (3 elements):
' 'ONE' 'TWO' 'THREE'
下列範例會定義分隔符陣列,其中包含標點符號和空格符。 將這個陣列連同 StringSplitOptions.RemoveEmptyEntries 的值一起傳遞至 Split(String[], StringSplitOptions) 方法,會傳回包含字串中個別字組的陣列。
string[] separators = { ",", ".", "!", "?", ";", ":", " " };
string value = "The handsome, energetic, young dog was playing with his smaller, more lethargic litter mate.";
string[] words = value.Split(separators, StringSplitOptions.RemoveEmptyEntries);
foreach (var word in words)
Console.WriteLine(word);
// The example displays the following output:
// The
// handsome
// energetic
// young
// dog
// was
// playing
// with
// his
// smaller
// more
// lethargic
// litter
// mate
let separators = [| ","; "."; "!"; "?"; ""; ":"; " " |]
let value = "The handsome, energetic, young dog was playing with his smaller, more lethargic litter mate."
let words = value.Split(separators, StringSplitOptions.RemoveEmptyEntries)
for word in words do
printfn $"${word}"
// The example displays the following output:
// The
// handsome
// energetic
// young
// dog
// was
// playing
// with
// his
// smaller
// more
// lethargic
// litter
// mate
Dim separators() As String = {",", ".", "!", "?", ";", ":", " "}
Dim value As String = "The handsome, energetic, young dog was playing with his smaller, more lethargic litter mate."
Dim words() As String = value.Split(separators, StringSplitOptions.RemoveEmptyEntries)
For Each word In words
Console.WriteLine(word)
Next
End Sub
' The example displays the following output:
'
' The
' handsome
' energetic
' young
' dog
' was
' playing
' with
' his
' smaller
' more
' lethargic
' litter
' mate
請注意,會呼叫 方法,並將 options
自變數設定為 StringSplitOptions.RemoveEmptyEntries。 這可防止傳回的陣列包含 String.Empty 值,這些值代表標點符號與空格符之間的空白子字串相符專案。
備註
當字串以一組已知的字串分隔時,您可以使用 Split 方法來將字串分隔成子字串。
傳回數位的元素中不包含分隔符字串。 例如,如果 separator
數位含字串 「--」 且目前字串實例的值是 「aa--bb--cc」。,則方法會傳回包含三個元素的數位:「aa」。、“bb” 和 「cc」。
如果這個實例不包含 separator
中的任何字串,則傳回的陣列是由包含這個實例的單一元素所組成。
如果 options
參數 RemoveEmptyEntries 且這個實例的長度為零,則方法會傳回空陣列。
separator
的每個元素都會定義由一或多個字元組成的個別分隔符。 如果 options
自變數是 None,而兩個分隔符是相鄰的,或是在這個實例的開頭或結尾找到分隔符,對應的陣列元素會包含 String.Empty。 例如,如果 separator
包含兩個元素 「-」 和 「_」,則字串實例的值會是 「-_aa-_」,而 options
自變數的值會 None,此方法會傳回具有下列五個元素的字元串數位:
String.Empty,代表索引0上「-」 子字串前面的空字串。
String.Empty,代表位於索引 0 的 “-” 子字串與索引 1 的 “_” 子字串之間的空字串。
“aa”。
String.Empty,代表索引 4 上 “-” 子字串後面的空字串。
String.Empty,代表索引 5 上 “_” 子字串後面的空字串。
分隔符陣列
如果 separator
中的任何專案是由多個字元所組成,則整個子字串會被視為分隔符。 例如,如果 separator
中的其中一個元素是 “10”,則嘗試分割字串 “This10is10a10string”。會傳回下列四個元素陣列: { “This”, “is”, “a”, “string.” }。
如果 separator
參數是 null
或不包含非空白字串,則空格符會假設為分隔符。 空格符是由 Unicode 標準所定義,Char.IsWhiteSpace 方法會傳回 true
傳遞至該字元。
若要傳遞 string[] separator
參數的 null
,您必須指出 null
的類型,以釐清呼叫與其他多載,例如 Split(Char[], StringSplitOptions)。 下列範例示範數種方式來明確識別此多載。
string phrase = "The quick brown fox";
_ = phrase.Split(default(string[]), StringSplitOptions.RemoveEmptyEntries);
_ = phrase.Split((string[]?)null, StringSplitOptions.RemoveEmptyEntries);
_ = phrase.Split(null as string[], StringSplitOptions.RemoveEmptyEntries);
let phrase = "The quick brown fox"
phrase.Split(Unchecked.defaultof<string[]>, StringSplitOptions.RemoveEmptyEntries) |> ignore
phrase.Split(null :> string[], StringSplitOptions.RemoveEmptyEntries) |> ignore
phrase.Split((null: string[]), StringSplitOptions.RemoveEmptyEntries) |> ignore
Dim phrase As String = "The quick brown fox"
Dim words() As String
words = phrase.Split(TryCast(Nothing, String()),
StringSplitOptions.RemoveEmptyEntries)
words = phrase.Split(New String() {},
StringSplitOptions.RemoveEmptyEntries)
比較詳細數據
Split 方法會擷取此字串中的子字串,這些子字串是以 separator
參數中的一或多個字串分隔,並傳回這些子字串做為陣列的元素。
Split 方法會使用區分大小寫的序數排序規則來執行比較來尋找分隔符。 如需單字、字串和序數排序的詳細資訊,請參閱 System.Globalization.CompareOptions 列舉。
Split 方法會忽略其值為 null
或空字串 (“”)的任何 separator
專案。
為了避免當 separator
中的字串有一般字元時產生模棱兩可的結果,Split 作業會從 實例值的開頭到結尾繼續,並且比對實例中等於分隔符 separator
中的第一個專案。 實例中遇到子字串的順序優先於 separator
中的項目順序。
例如,請考慮值為 「abcdef」 的實例。 如果 separator
的第一個專案是 「ef」,而第二個元素是 「bcde」,則分割作業的結果會是包含兩個元素 「a」 和 「f」 的字串陣列。 這是因為在遇到子字串 「f」 之前,遇到 實例 「bcde」 中的子字串,並符合 separator
中的專案。
不過,如果 separator
的第一個元素是 “bcd”,而第二個元素是 “bc”,則分割作業的結果會是包含兩個元素 “a” 和 “ef” 的字符串陣列。 這是因為 「bcd」 是 separator
中符合 實例中分隔符的第一個分隔符。 如果分隔符的順序反轉,因此第一個元素是 “bc”,而第二個元素是 “bcd”,則結果會是包含兩個元素 “a” 和 “def” 的字符串陣列。
效能考慮
Split 方法會配置傳回數位物件的記憶體,以及每個數位元素的 String 物件。 如果您的應用程式需要最佳效能,或管理記憶體配置在應用程式中很重要,請考慮使用 IndexOf 或 IndexOfAny 方法,以及選擇性地使用 Compare 方法,在字串中尋找子字串串。
如果您要在分隔字元分割字串,請使用 IndexOf 或 IndexOfAny 方法來找出字串中的分隔字元。 如果您要在分隔符字串分割字串,請使用 IndexOf 或 IndexOfAny 方法來找出分隔符字串的第一個字元。 然後使用 Compare 方法來判斷該第一個字元後面的字元是否等於分隔符字串的其餘字元。
此外,如果使用相同的字元集來分割多個 Split 方法呼叫中的字元串,請考慮在每個方法呼叫中建立單一數位並參考它。 這可大幅減少每個方法呼叫的額外額外負荷。
給呼叫者的注意事項
在 .NET Framework 3.5 和舊版中,如果傳遞 Split(Char[]) 方法的 separator
null
或不包含任何字元,則方法會使用稍微不同的空格符集來分割字符串,而不是 Trim(Char[]) 方法來修剪字串。 從 .NET Framework 4 開始,這兩種方法都會使用相同的 Unicode 空格符集。
適用於
Split(String, StringSplitOptions)
將字串分割成以提供的字串分隔符為基礎的子字串。
public string[] Split (string? separator, StringSplitOptions options = System.StringSplitOptions.None);
public string[] Split (string separator, StringSplitOptions options = System.StringSplitOptions.None);
member this.Split : string * StringSplitOptions -> string[]
Public Function Split (separator As String, Optional options As StringSplitOptions = System.StringSplitOptions.None) As String()
參數
- separator
- String
分隔此字串中子字串的字串。
- options
- StringSplitOptions
列舉值的位元組合,指定是否要修剪子字串並包含空子字串。
傳回
陣列,其專案包含這個實例的子字串,並以 separator
分隔。
適用於
Split(Char[])
根據指定的分隔字元,將字串分割成子字串。
public:
cli::array <System::String ^> ^ Split(... cli::array <char> ^ separator);
public string[] Split (params char[] separator);
public string[] Split (params char[]? separator);
member this.Split : char[] -> string[]
Public Function Split (ParamArray separator As Char()) As String()
參數
- separator
- Char[]
分隔字元的陣列、不包含分隔符的空陣列,或 null
。
傳回
陣列,其專案包含這個實例中的子字串,並以 separator
中的一或多個字元分隔。 如需詳細資訊,請參閱一節。
範例
下列範例示範如何將空格符(
)和製表元(\t
)視為分隔符,從文本塊中擷取個別單字。 要分割的字串包含這兩個字元。
string s = "Today\tI'm going to school";
string[] subs = s.Split(' ', '\t');
foreach (var sub in subs)
{
Console.WriteLine($"Substring: {sub}");
}
// This example produces the following output:
//
// Substring: Today
// Substring: I'm
// Substring: going
// Substring: to
// Substring: school
let s = "Today\tI'm going to school"
let subs = s.Split(' ', '\t')
for sub in subs do
printfn $"Substring: {sub}"
// This example produces the following output:
//
// Substring: Today
// Substring: I'm
// Substring: going
// Substring: to
// Substring: school
Dim s As String = "Today" & vbTab & "I'm going to school"
Dim subs As String() = s.Split(" "c, Char.Parse(vbTab))
For Each substring In subs
Console.WriteLine("Substring: " & substring)
Next
' This example produces the following output:
'
' Substring: Today
' Substring: I 'm
' Substring: going
' Substring: to
' Substring: school
備註
當字串以一組已知的字元分隔時,您可以使用 Split(Char[]) 方法來將字串分隔成子字串。
傳回數位元素中不包含分隔符。 例如,如果分隔符陣列包含字元 「-」 且目前字串實例的值是 「aa-bb-cc」,則方法會傳回包含三個元素的陣列:「aa」、“bb” 和 “cc”。
如果這個實例不包含 separator
中的任何字元,則傳回的陣列是由包含這個實例的單一元素所組成。
separator
的每個元素都會定義個別的分隔符。 如果兩個分隔符相鄰,或在此實體的開頭或結尾找到分隔符,則傳回陣列中的對應專案包含 Empty。
下表顯示一些範例。
語言 | 字串值 | 分隔符 | 傳回的陣列 |
---|---|---|---|
C# | "42, 12, 19" | new Char[] {',', ' '} | {"42", "", "12", "", "19"} |
Visual Basic | "42, 12, 19" | Char() = {“,”c, “ ”c}) | {"42", "", "12", "", "19"} |
C# | "42..12..19." | new Char[] {'.'} | {"42", "", "12", "", "19", ""} |
Visual Basic | "42..12..19." | Char() = {“.”c} | {"42", "", "12", "", "19", ""} |
C# | “香蕉” | new Char[] {'.'} | {“香蕉”} |
Visual Basic | “香蕉” | Char() = {“.”c} | {“香蕉”} |
C# | “達布\n斯瑪律巴” | new Char[] {} | {“Darb”, “Smarba”} |
Visual Basic | “Darb” & vbLf & “Smarba” | Char() = {} | {“Darb”, “Smarba”} |
C# | “達布\n斯瑪律巴” | 零 | {“Darb”, “Smarba”} |
Visual Basic | “Darb” & vbLf & “Smarba” | 無 | {“Darb”, “Smarba”} |
分隔符陣列
分隔符的每個元素都會定義由單一字元組成的個別分隔符。
如果 separator
自變數 null
或不包含任何字元,則方法會將空格符視為分隔符。 空格符是由 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 物件。 如果您的應用程式需要最佳效能,或管理記憶體配置在應用程式中很重要,請考慮使用 IndexOf 或 IndexOfAny 方法。 您也可以選擇使用 Compare 方法來尋找字串中的子字串。
若要在分隔符處分割字串,請使用 IndexOf 或 IndexOfAny 方法來尋找字串中的分隔字元。 若要在分隔符字串分割字串,請使用 IndexOf 或 IndexOfAny 方法來找出分隔符字串的第一個字元。 然後使用 Compare 方法來判斷該第一個字元後面的字元是否等於分隔符字串的其餘字元。
此外,如果使用相同的字元集來分割多個 Split 方法呼叫中的字元串,請考慮在每個方法呼叫中建立單一數位並參考它。 這可大幅減少每個方法呼叫的額外額外負荷。
給呼叫者的注意事項
在 .NET Framework 3.5 和舊版中,如果傳遞 Split(Char[]) 方法的 separator
null
或不包含任何字元,則方法會使用稍微不同的空格符集來分割字符串,而不是 Trim(Char[]) 方法來修剪字串。 從 .NET Framework 4 開始,這兩種方法都會使用相同的 Unicode 空格符集。
另請參閱
- Char
- Concat(Object)
- Insert(Int32, String)
- Join(String, String[])
- Remove(Int32, Int32)
- Replace(Char, Char)
- Substring(Int32)
- Trim(Char[])
適用於
Split(Char[], Int32)
根據指定的分隔字元,將字串分割成最大子字串數目。
public:
cli::array <System::String ^> ^ Split(cli::array <char> ^ separator, int count);
public string[] Split (char[] separator, int count);
public string[] Split (char[]? separator, int count);
member this.Split : char[] * int -> string[]
Public Function Split (separator As Char(), count As Integer) As String()
參數
- separator
- Char[]
此字串中分隔子字串的字元陣列、不含分隔符的空陣列,或 null
。
- count
- Int32
要傳回的子字串數目上限。
傳回
陣列,其專案包含這個實例中的子字串,並以 separator
中的一或多個字元分隔。 如需詳細資訊,請參閱一節。
例外狀況
count
為負數。
範例
下列範例示範如何使用 count
來限制 Split所傳回的字串數目。
string name = "Alex Johnson III";
string[] subs = name.Split(null, 2);
string firstName = subs[0];
string lastName;
if (subs.Length > 1)
{
lastName = subs[1];
}
// firstName = "Alex"
// lastName = "Johnson III"
let name = "Alex Johnson III"
let subs = name.Split(null, 2)
let firstName = subs[0]
let lastName =
if subs.Length > 1 then
subs[1]
else
""
// firstName = "Alex"
// lastName = "Johnson III"
Console.WriteLine("What is your name?")
Dim name As String = Console.ReadLine()
Dim substrings = name.Split(" "c, count:=2)
Dim firstName As String = substrings(0)
Dim lastName As String
If substrings.Length > 1 Then
lastName = substrings(1)
End If
Console.WriteLine("firstName = ""{0}""", firstName)
Console.WriteLine("lastName = ""{0}""", lastName)
' If the user enters "Alex Johnson III":
' firstName = "Alex"
' lastName = "Johnson III"
備註
傳回數位元素中不包含分隔符。
如果這個實例不包含 separator
中的任何字元,則傳回的陣列是由包含這個實例的單一元素所組成。 如果 count
為零,則會傳回空陣列。
如果 separator
參數是 null
或不包含任何字元,則空格符會假設為分隔符。 空格符是由 Unicode 標準所定義,Char.IsWhiteSpace 方法會傳回 true
傳遞至該字元。
separator
的每個元素都會定義個別的分隔符。 如果兩個分隔符相鄰,或在此實體的開頭或結尾找到分隔符,則對應的陣列元素會包含 Empty。
如果這個實例中有超過 count
個子字串,第一個 count - 1
子字串會在傳回值的第一個 count - 1
元素中傳回,而這個實例中的其餘字元則會傳回傳回值的最後一個專案。
如果 count
大於子字串的數目,則會傳回可用的子字串,而且不會擲回任何例外狀況。
下表顯示一些範例。
語言 | 字串值 | 分隔符 | 傳回的陣列 |
---|---|---|---|
C# | "42, 12, 19" | new Char[] {',', ' '} | {"42", "", "12", "", "19"} |
Visual Basic | "42, 12, 19" | Char() = {“,”c, “ ”c}) | {"42", "", "12", "", "19"} |
C# | "42..12..19." | new Char[] {'.'} | {"42", "", "12", "", "19", ""} |
Visual Basic | "42..12..19." | Char() = {“.”c} | {"42", "", "12", "", "19", ""} |
C# | “香蕉” | new Char[] {'.'} | {“香蕉”} |
Visual Basic | “香蕉” | Char() = {“.”c} | {“香蕉”} |
C# | “達布\n斯瑪律巴” | new Char[] {} | {“Darb”, “Smarba”} |
Visual Basic | “Darb” & vbLf & “Smarba” | Char() = {} | {“Darb”, “Smarba”} |
C# | “達布\n斯瑪律巴” | 零 | {“Darb”, “Smarba”} |
Visual Basic | “Darb” & vbLf & “Smarba” | 無 | {“Darb”, “Smarba”} |
效能考慮
Split 方法會配置傳回數位物件的記憶體,以及每個數位元素的 String 物件。 如果您的應用程式需要最佳效能,或管理記憶體配置在應用程式中很重要,請考慮使用 IndexOf 或 IndexOfAny 方法,以及選擇性地使用 Compare 方法,在字串中尋找子字串串。
如果您要在分隔字元分割字串,請使用 IndexOf 或 IndexOfAny 方法來找出字串中的分隔字元。 如果您要在分隔符字串分割字串,請使用 IndexOf 或 IndexOfAny 方法來找出分隔符字串的第一個字元。 然後使用 Compare 方法來判斷該第一個字元後面的字元是否等於分隔符字串的其餘字元。
此外,如果使用相同的字元集來分割多個 Split 方法呼叫中的字元串,請考慮在每個方法呼叫中建立單一數位並參考它。 這可大幅減少每個方法呼叫的額外額外負荷。
給呼叫者的注意事項
在 .NET Framework 3.5 和舊版中,如果傳遞 Split(Char[]) 方法的 separator
null
或不包含任何字元,則方法會使用稍微不同的空格符集來分割字符串,而不是 Trim(Char[]) 方法來修剪字串。 從 .NET Framework 4 開始,這兩種方法都會使用相同的 Unicode 空格符集。
另請參閱
- Char
- Array
- Int32
- Concat(Object)
- Insert(Int32, String)
- Join(String, String[])
- Remove(Int32, Int32)
- Replace(Char, Char)
- Substring(Int32)
- Trim(Char[])
適用於
Split(Char, StringSplitOptions)
根據指定的分隔字元,將字串分割成子字串,並選擇性地將字串分割成子字串。
public string[] Split (char separator, StringSplitOptions options = System.StringSplitOptions.None);
member this.Split : char * StringSplitOptions -> string[]
Public Function Split (separator As Char, Optional options As StringSplitOptions = System.StringSplitOptions.None) As String()
參數
- separator
- Char
分隔此字串中子字串的字元。
- options
- StringSplitOptions
列舉值的位元組合,指定是否要修剪子字串並包含空子字串。
傳回
陣列,其專案包含這個實例的子字串,並以 separator
分隔。
適用於
Split(ReadOnlySpan<Char>)
根據指定的分隔字元,將字串分割成子字串。
public:
cli::array <System::String ^> ^ Split(ReadOnlySpan<char> separator);
public string[] Split (scoped ReadOnlySpan<char> separator);
member this.Split : ReadOnlySpan<char> -> string[]
Public Function Split (separator As ReadOnlySpan(Of Char)) As String()
參數
- separator
- ReadOnlySpan<Char>
分隔字元的範圍,或不含分隔符的空白範圍。
傳回
陣列,其專案包含這個實例中的子字串,並以 separator
中的一或多個字元分隔。
適用於
Split(String[], Int32, StringSplitOptions)
根據指定的分隔字串和選擇性選項,將字串分割成子字串數目上限。
public:
cli::array <System::String ^> ^ Split(cli::array <System::String ^> ^ separator, int count, StringSplitOptions options);
public string[] Split (string[] separator, int count, StringSplitOptions options);
public string[] Split (string[]? separator, int count, StringSplitOptions options);
[System.Runtime.InteropServices.ComVisible(false)]
public string[] Split (string[] separator, int count, StringSplitOptions options);
member this.Split : string[] * int * StringSplitOptions -> string[]
[<System.Runtime.InteropServices.ComVisible(false)>]
member this.Split : string[] * int * StringSplitOptions -> string[]
Public Function Split (separator As String(), count As Integer, options As StringSplitOptions) As String()
參數
- separator
- String[]
在這裡字串中分隔子字串的字串、不含分隔符的空數組,或 null
。
- count
- Int32
要傳回的子字串數目上限。
- options
- StringSplitOptions
列舉值的位元組合,指定是否要修剪子字串並包含空子字串。
傳回
陣列,其專案包含此字串中的子字串,並以 separator
中的一或多個字串分隔。 如需詳細資訊,請參閱一節。
- 屬性
例外狀況
count
為負數。
options
不是其中一個 StringSplitOptions 值。
範例
下列範例會使用 StringSplitOptions 列舉來包含或排除 Split 方法所產生的子字串。
// This example demonstrates the String.Split(Char[], Boolean) and
// String.Split(Char[], Int32, Boolean) methods
using namespace System;
void Show( array<String^>^entries )
{
Console::WriteLine( "The return value contains these {0} elements:", entries->Length );
System::Collections::IEnumerator^ myEnum = entries->GetEnumerator();
while ( myEnum->MoveNext() )
{
String^ entry = safe_cast<String^>(myEnum->Current);
Console::Write( "<{0}>", entry );
}
Console::Write( "{0}{0}", Environment::NewLine );
}
int main()
{
String^ s = ",one,,,two,,,,,three,,";
array<Char>^sep = gcnew array<Char>{
','
};
array<String^>^result;
//
Console::WriteLine( "The original string is \"{0}\".", s );
Console::WriteLine( "The separation character is '{0}'.", sep[ 0 ] );
Console::WriteLine();
//
Console::WriteLine( "Split the string and return all elements:" );
result = s->Split( sep, StringSplitOptions::None );
Show( result );
//
Console::WriteLine( "Split the string and return all non-empty elements:" );
result = s->Split( sep, StringSplitOptions::RemoveEmptyEntries );
Show( result );
//
Console::WriteLine( "Split the string and return 2 elements:" );
result = s->Split( sep, 2, StringSplitOptions::None );
Show( result );
//
Console::WriteLine( "Split the string and return 2 non-empty elements:" );
result = s->Split( sep, 2, StringSplitOptions::RemoveEmptyEntries );
Show( result );
}
/*
This example produces the following results:
The original string is ",one,,,two,,,,,three,,".
The separation character is ','.
Split the string and return all elements:
The return value contains these 12 elements:
<><one><><><two><><><><><three><><>
Split the string and return all non-empty elements:
The return value contains these 3 elements:
<one><two><three>
Split the string and return 2 elements:
The return value contains these 2 elements:
<><one,,,two,,,,,three,,>
Split the string and return 2 non-empty elements:
The return value contains these 2 elements:
<one><,,two,,,,,three,,>
*/
// This example demonstrates the String.Split() methods that use
// the StringSplitOptions enumeration.
// Example 1: Split a string delimited by characters
Console.WriteLine("1) Split a string delimited by characters:\n");
string s1 = ",ONE,, TWO,, , THREE,,";
char[] charSeparators = new char[] { ',' };
string[] result;
Console.WriteLine($"The original string is: \"{s1}\".");
Console.WriteLine($"The delimiter character is: '{charSeparators[0]}'.\n");
// Split the string and return all elements
Console.WriteLine("1a) Return all elements:");
result = s1.Split(charSeparators, StringSplitOptions.None);
Show(result);
// Split the string and return all elements with whitespace trimmed
Console.WriteLine("1b) Return all elements with whitespace trimmed:");
result = s1.Split(charSeparators, StringSplitOptions.TrimEntries);
Show(result);
// Split the string and return all non-empty elements
Console.WriteLine("1c) Return all non-empty elements:");
result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// Split the string and return all non-whitespace elements with whitespace trimmed
Console.WriteLine("1d) Return all non-whitespace elements with whitespace trimmed:");
result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
Show(result);
// Split the string into only two elements, keeping the remainder in the last match
Console.WriteLine("1e) Split into only two elements:");
result = s1.Split(charSeparators, 2, StringSplitOptions.None);
Show(result);
// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("1f) Split into only two elements with whitespace trimmed:");
result = s1.Split(charSeparators, 2, StringSplitOptions.TrimEntries);
Show(result);
// Split the string into only two non-empty elements, keeping the remainder in the last match
Console.WriteLine("1g) Split into only two non-empty elements:");
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("1h) Split into only two non-whitespace elements with whitespace trimmed:");
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
Show(result);
// Example 2: Split a string delimited by another string
Console.WriteLine("2) Split a string delimited by another string:\n");
string s2 = "[stop]" +
"ONE[stop] [stop]" +
"TWO [stop][stop] [stop]" +
"THREE[stop][stop] ";
string[] stringSeparators = new string[] { "[stop]" };
Console.WriteLine($"The original string is: \"{s2}\".");
Console.WriteLine($"The delimiter string is: \"{stringSeparators[0]}\".\n");
// Split the string and return all elements
Console.WriteLine("2a) Return all elements:");
result = s2.Split(stringSeparators, StringSplitOptions.None);
Show(result);
// Split the string and return all elements with whitespace trimmed
Console.WriteLine("2b) Return all elements with whitespace trimmed:");
result = s2.Split(stringSeparators, StringSplitOptions.TrimEntries);
Show(result);
// Split the string and return all non-empty elements
Console.WriteLine("2c) Return all non-empty elements:");
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// Split the string and return all non-whitespace elements with whitespace trimmed
Console.WriteLine("2d) Return all non-whitespace elements with whitespace trimmed:");
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
Show(result);
// Split the string into only two elements, keeping the remainder in the last match
Console.WriteLine("2e) Split into only two elements:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.None);
Show(result);
// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("2f) Split into only two elements with whitespace trimmed:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.TrimEntries);
Show(result);
// Split the string into only two non-empty elements, keeping the remainder in the last match
Console.WriteLine("2g) Split into only two non-empty elements:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("2h) Split into only two non-whitespace elements with whitespace trimmed:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
Show(result);
// Display the array of separated strings using a local function
void Show(string[] entries)
{
Console.WriteLine($"The return value contains these {entries.Length} elements:");
foreach (string entry in entries)
{
Console.Write($"<{entry}>");
}
Console.Write("\n\n");
}
/*
This example produces the following results:
1) Split a string delimited by characters:
The original string is: ",ONE,, TWO,, , THREE,,".
The delimiter character is: ','.
1a) Return all elements:
The return value contains these 9 elements:
<><ONE><>< TWO><>< >< THREE><><>
1b) Return all elements with whitespace trimmed:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>
1c) Return all non-empty elements:
The return value contains these 4 elements:
<ONE>< TWO>< >< THREE>
1d) Return all non-whitespace elements with whitespace trimmed:
The return value contains these 3 elements:
<ONE><TWO><THREE>
1e) Split into only two elements:
The return value contains these 2 elements:
<><ONE,, TWO,, , THREE,,>
1f) Split into only two elements with whitespace trimmed:
The return value contains these 2 elements:
<><ONE,, TWO,, , THREE,,>
1g) Split into only two non-empty elements:
The return value contains these 2 elements:
<ONE>< TWO,, , THREE,,>
1h) Split into only two non-whitespace elements with whitespace trimmed:
The return value contains these 2 elements:
<ONE><TWO,, , THREE,,>
2) Split a string delimited by another string:
The original string is: "[stop]ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] ".
The delimiter string is: "[stop]".
2a) Return all elements:
The return value contains these 9 elements:
<><ONE>< ><TWO ><>< ><THREE><>< >
2b) Return all elements with whitespace trimmed:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>
2c) Return all non-empty elements:
The return value contains these 6 elements:
<ONE>< ><TWO >< ><THREE>< >
2d) Return all non-whitespace elements with whitespace trimmed:
The return value contains these 3 elements:
<ONE><TWO><THREE>
2e) Split into only two elements:
The return value contains these 2 elements:
<><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] >
2f) Split into only two elements with whitespace trimmed:
The return value contains these 2 elements:
<><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop]>
2g) Split into only two non-empty elements:
The return value contains these 2 elements:
<ONE>< [stop]TWO [stop][stop] [stop]THREE[stop][stop] >
2h) Split into only two non-whitespace elements with whitespace trimmed:
The return value contains these 2 elements:
<ONE><TWO [stop][stop] [stop]THREE[stop][stop]>
*/
// This example demonstrates the String.Split() methods that use
// the StringSplitOptions enumeration.
// Display the array of separated strings using a local function
let show (entries: string[]) =
printfn $"The return value contains these {entries.Length} elements:"
for entry in entries do
printf $"<{entry}>"
printf "\n\n"
// Example 1: Split a string delimited by characters
printfn "1) Split a string delimited by characters:\n"
let s1 = ",ONE,, TWO,, , THREE,,"
let charSeparators = [| ',' |]
printfn $"The original string is: \"{s1}\"."
printfn $"The delimiter character is: '{charSeparators[0]}'.\n"
// Split the string and return all elements
printfn "1a) Return all elements:"
let result = s1.Split(charSeparators, StringSplitOptions.None)
show result
// Split the string and return all elements with whitespace trimmed
printfn "1b) Return all elements with whitespace trimmed:"
let result = s1.Split(charSeparators, StringSplitOptions.TrimEntries)
show result
// Split the string and return all non-empty elements
printfn "1c) Return all non-empty elements:"
let result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries)
show result
// Split the string and return all non-whitespace elements with whitespace trimmed
printfn "1d) Return all non-whitespace elements with whitespace trimmed:"
let result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)
show result
// Split the string into only two elements, keeping the remainder in the last match
printfn "1e) Split into only two elements:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.None)
show result
// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
printfn "1f) Split into only two elements with whitespace trimmed:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.TrimEntries)
show result
// Split the string into only two non-empty elements, keeping the remainder in the last match
printfn "1g) Split into only two non-empty elements:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
show result
// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
printfn "1h) Split into only two non-whitespace elements with whitespace trimmed:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)
show result
// Example 2: Split a string delimited by another string
printfn "2) Split a string delimited by another string:\n"
let s2 = "[stop]" +
"ONE[stop] [stop]" +
"TWO [stop][stop] [stop]" +
"THREE[stop][stop] "
let stringSeparators = [| "[stop]" |]
printfn $"The original string is: \"{s2}\"."
printfn $"The delimiter string is: \"{stringSeparators[0]}\".\n"
// Split the string and return all elements
printfn "2a) Return all elements:"
let result = s2.Split(stringSeparators, StringSplitOptions.None)
show result
// Split the string and return all elements with whitespace trimmed
printfn "2b) Return all elements with whitespace trimmed:"
let result = s2.Split(stringSeparators, StringSplitOptions.TrimEntries)
show result
// Split the string and return all non-empty elements
printfn "2c) Return all non-empty elements:"
let result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)
show result
// Split the string and return all non-whitespace elements with whitespace trimmed
printfn "2d) Return all non-whitespace elements with whitespace trimmed:"
let result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)
show result
// Split the string into only two elements, keeping the remainder in the last match
printfn "2e) Split into only two elements:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.None)
show result
// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
printfn "2f) Split into only two elements with whitespace trimmed:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.TrimEntries)
show result
// Split the string into only two non-empty elements, keeping the remainder in the last match
printfn "2g) Split into only two non-empty elements:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
show result
// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
printfn "2h) Split into only two non-whitespace elements with whitespace trimmed:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)
show result
(*
This example produces the following results:
1) Split a string delimited by characters:
The original string is: ",ONE,, TWO,, , THREE,,".
The delimiter character is: ','.
1a) Return all elements:
The return value contains these 9 elements:
<><ONE><>< TWO><>< >< THREE><><>
1b) Return all elements with whitespace trimmed:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>
1c) Return all non-empty elements:
The return value contains these 4 elements:
<ONE>< TWO>< >< THREE>
1d) Return all non-whitespace elements with whitespace trimmed:
The return value contains these 3 elements:
<ONE><TWO><THREE>
1e) Split into only two elements:
The return value contains these 2 elements:
<><ONE,, TWO,, , THREE,,>
1f) Split into only two elements with whitespace trimmed:
The return value contains these 2 elements:
<><ONE,, TWO,, , THREE,,>
1g) Split into only two non-empty elements:
The return value contains these 2 elements:
<ONE>< TWO,, , THREE,,>
1h) Split into only two non-whitespace elements with whitespace trimmed:
The return value contains these 2 elements:
<ONE><TWO,, , THREE,,>
2) Split a string delimited by another string:
The original string is: "[stop]ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] ".
The delimiter string is: "[stop]".
2a) Return all elements:
The return value contains these 9 elements:
<><ONE>< ><TWO ><>< ><THREE><>< >
2b) Return all elements with whitespace trimmed:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>
2c) Return all non-empty elements:
The return value contains these 6 elements:
<ONE>< ><TWO >< ><THREE>< >
2d) Return all non-whitespace elements with whitespace trimmed:
The return value contains these 3 elements:
<ONE><TWO><THREE>
2e) Split into only two elements:
The return value contains these 2 elements:
<><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] >
2f) Split into only two elements with whitespace trimmed:
The return value contains these 2 elements:
<><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop]>
2g) Split into only two non-empty elements:
The return value contains these 2 elements:
<ONE>< [stop]TWO [stop][stop] [stop]THREE[stop][stop] >
2h) Split into only two non-whitespace elements with whitespace trimmed:
The return value contains these 2 elements:
<ONE><TWO [stop][stop] [stop]THREE[stop][stop]>
*)
Public Shared Sub StringSplitOptionsExamples()
' This example demonstrates the String.Split() methods that use
' the StringSplitOptions enumeration.
' Example 1: Split a string delimited by characters
Console.WriteLine("1) Split a string delimited by characters:" & vbCrLf)
Dim s1 As String = ",ONE,, TWO,, , THREE,,"
Dim charSeparators() As Char = {","c}
Dim result() As String
Console.WriteLine("The original string is: ""{0}"".", s1)
Console.WriteLine("The delimiter character is: '{0}'." & vbCrLf, charSeparators(0))
' Split the string and return all elements
Console.WriteLine("1a) Return all elements:")
result = s1.Split(charSeparators, StringSplitOptions.None)
Show(result)
' Split the string and return all elements with whitespace trimmed
Console.WriteLine("1b) Return all elements with whitespace trimmed:")
result = s1.Split(charSeparators, StringSplitOptions.TrimEntries)
Show(result)
' Split the string and return all non-empty elements
Console.WriteLine("1c) Return all non-empty elements:")
result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries)
Show(result)
' Split the string and return all non-whitespace elements with whitespace trimmed
Console.WriteLine("1d) Return all non-whitespace elements with whitespace trimmed:")
result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries)
Show(result)
' Split the string into only two elements, keeping the remainder in the last match
Console.WriteLine("1e) Split into only two elements:")
result = s1.Split(charSeparators, 2, StringSplitOptions.None)
Show(result)
' Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("1f) Split into only two elements with whitespace trimmed:")
result = s1.Split(charSeparators, 2, StringSplitOptions.TrimEntries)
Show(result)
' Split the string into only two non-empty elements, keeping the remainder in the last match
Console.WriteLine("1g) Split into only two non-empty elements:")
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
Show(result)
' Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("1h) Split into only two non-whitespace elements with whitespace trimmed:")
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries)
Show(result)
' Example 2: Split a string delimited by another string
Console.WriteLine("2) Split a string delimited by another string:" & vbCrLf)
Dim s2 As String = "[stop]" +
"ONE[stop] [stop]" +
"TWO [stop][stop] [stop]" +
"THREE[stop][stop] "
Dim stringSeparators() As String = {"[stop]"}
Console.WriteLine("The original string is: ""{0}"".", s2)
Console.WriteLine("The delimiter string is: ""{0}""." & vbCrLf, stringSeparators(0))
' Split the string and return all elements
Console.WriteLine("2a) Return all elements:")
result = s2.Split(stringSeparators, StringSplitOptions.None)
Show(result)
' Split the string and return all elements with whitespace trimmed
Console.WriteLine("2b) Return all elements with whitespace trimmed:")
result = s2.Split(stringSeparators, StringSplitOptions.TrimEntries)
Show(result)
' Split the string and return all non-empty elements
Console.WriteLine("2c) Return all non-empty elements:")
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)
Show(result)
' Split the string and return all non-whitespace elements with whitespace trimmed
Console.WriteLine("2d) Return all non-whitespace elements with whitespace trimmed:")
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries)
Show(result)
' Split the string into only two elements, keeping the remainder in the last match
Console.WriteLine("2e) Split into only two elements:")
result = s2.Split(stringSeparators, 2, StringSplitOptions.None)
Show(result)
' Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("2f) Split into only two elements with whitespace trimmed:")
result = s2.Split(stringSeparators, 2, StringSplitOptions.TrimEntries)
Show(result)
' Split the string into only two non-empty elements, keeping the remainder in the last match
Console.WriteLine("2g) Split into only two non-empty elements:")
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
Show(result)
' Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("2h) Split into only two non-whitespace elements with whitespace trimmed:")
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries)
Show(result)
End Sub
' Display the array of separated strings.
Public Shared Sub Show(ByVal entries() As String)
Console.WriteLine("The return value contains these {0} elements:", entries.Length)
Dim entry As String
For Each entry In entries
Console.Write("<{0}>", entry)
Next entry
Console.Write(vbCrLf & vbCrLf)
End Sub
'This example produces the following results:
'
' 1) Split a string delimited by characters:
'
' The original string is: ",ONE,, TWO,, , THREE,,".
' The delimiter character is: ','.
'
' 1a) Return all elements:
' The return value contains these 9 elements:
' <><ONE><>< TWO><>< >< THREE><><>
'
' 1b) Return all elements with whitespace trimmed:
' The return value contains these 9 elements:
' <><ONE><><TWO><><><THREE><><>
'
' 1c) Return all non-empty elements:
' The return value contains these 4 elements:
' <ONE>< TWO>< >< THREE>
'
' 1d) Return all non-whitespace elements with whitespace trimmed:
' The return value contains these 3 elements:
' <ONE><TWO><THREE>
'
' 1e) Split into only two elements:
' The return value contains these 2 elements:
' <><ONE,, TWO,, , THREE,,>
'
' 1f) Split into only two elements with whitespace trimmed:
' The return value contains these 2 elements:
' <><ONE,, TWO,, , THREE,,>
'
' 1g) Split into only two non-empty elements:
' The return value contains these 2 elements:
' <ONE>< TWO,, , THREE,,>
'
' 1h) Split into only two non-whitespace elements with whitespace trimmed:
' The return value contains these 2 elements:
' <ONE><TWO,, , THREE,,>
'
' 2) Split a string delimited by another string:
'
' The original string is: "[stop]ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] ".
' The delimiter string is: "[stop]".
'
' 2a) Return all elements:
' The return value contains these 9 elements:
' <><ONE>< ><TWO ><>< ><THREE><>< >
'
' 2b) Return all elements with whitespace trimmed:
' The return value contains these 9 elements:
' <><ONE><><TWO><><><THREE><><>
'
' 2c) Return all non-empty elements:
' The return value contains these 6 elements:
' <ONE>< ><TWO >< ><THREE>< >
'
' 2d) Return all non-whitespace elements with whitespace trimmed:
' The return value contains these 3 elements:
' <ONE><TWO><THREE>
'
' 2e) Split into only two elements:
' The return value contains these 2 elements:
' <><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] >
'
' 2f) Split into only two elements with whitespace trimmed:
' The return value contains these 2 elements:
' <><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop]>
'
' 2g) Split into only two non-empty elements:
' The return value contains these 2 elements:
' <ONE>< [stop]TWO [stop][stop] [stop]THREE[stop][stop] >
'
' 2h) Split into only two non-whitespace elements with whitespace trimmed:
' The return value contains these 2 elements:
' <ONE><TWO [stop][stop] [stop]THREE[stop][stop]>
'
備註
傳回數位的元素中不包含分隔符字串。
如果這個實例不包含 separator
中的任何字串,或 count
參數為 1,則傳回的陣列會包含包含這個實例的單一元素。
如果 separator
參數是 null
或不包含任何字元,則空格符會假設為分隔符。 空格符是由 Unicode 標準所定義,Char.IsWhiteSpace 方法會傳回 true
傳遞至該字元。
若要傳遞 string[] separator
參數的 null
,您必須指出 null
的類型,以釐清呼叫與其他多載,例如 Split(Char[], Int32, StringSplitOptions)。 下列範例示範數種方式來明確識別此多載。
string phrase = "The quick brown fox";
_ = phrase.Split(default(string[]), 3, StringSplitOptions.RemoveEmptyEntries);
_ = phrase.Split((string[]?)null, 3, StringSplitOptions.RemoveEmptyEntries);
_ = phrase.Split(null as string[], 3, StringSplitOptions.RemoveEmptyEntries);
let phrase = "The quick brown fox"
phrase.Split(Unchecked.defaultof<string[]>, 3, StringSplitOptions.RemoveEmptyEntries) |> ignore
phrase.Split(null :> string[], 3, StringSplitOptions.RemoveEmptyEntries) |> ignore
phrase.Split((null: string[]), 3, StringSplitOptions.RemoveEmptyEntries) |> ignore
Dim phrase As String = "The quick brown fox"
Dim words() As String
words = phrase.Split(TryCast(Nothing, String()), 3,
StringSplitOptions.RemoveEmptyEntries)
words = phrase.Split(New String() {}, 3,
StringSplitOptions.RemoveEmptyEntries)
如果 count
參數為零,或 options
參數 RemoveEmptyEntries 且這個實例的長度為零,則會傳回空陣列。
separator
的每個元素都會定義由一或多個字元組成的個別分隔符。 如果 options
參數是 None,而且兩個分隔符是相鄰的,或是在這個實例的開頭或結尾找到分隔符,則對應的陣列元素會包含 Empty。
如果這個實例中有超過 count
個子字串,第一個 count
減 1 個子字串會在傳回值的第一個 count
減 1 個元素中傳回,而這個實例中的其餘字元會在傳回值的最後一個元素中傳回。
如果 count
大於子字串的數目,則會傳回可用的子字串,而且不會擲回任何例外狀況。
分隔符陣列
如果 separator
中的任何專案是由多個字元所組成,則整個子字串會被視為分隔符。 例如,如果 separator
中的其中一個元素是 “10”,則嘗試分割字符串 “This10is10a10string”。會傳回這個四個元素陣列: { “This”, “is”, “a”, “string.” }。
比較詳細數據
Split 方法會擷取此字串中的子字串,這些子字串是以 separator
參數中的一或多個字串分隔,並傳回這些子字串做為陣列的元素。
Split 方法會使用區分大小寫的序數排序規則來執行比較來尋找分隔符。 如需單字、字串和序數排序的詳細資訊,請參閱 System.Globalization.CompareOptions 列舉。
Split 方法會忽略其值為 null
或空字串 (“”)的任何 separator
專案。
為了避免當 separator
中的字串有一般字元時產生模棱兩可的結果,Split 方法會從 實例值的開頭到結尾繼續,並且比對實例中等於分隔符 separator
中的第一個專案。 實例中遇到子字串的順序優先於 separator
中的項目順序。
例如,請考慮值為 「abcdef」 的實例。 如果 separator
中的第一個專案是 「ef」,而第二個元素是 「bcde」,則分割作業的結果會是 “a” 和 “f”。 這是因為在遇到子字串 「f」 之前,遇到 實例 「bcde」 中的子字串,並符合 separator
中的專案。
不過,如果 separator
的第一個元素是 “bcd”,而第二個元素是 “bc”,則分割作業的結果會是 “a” 和 “ef”。 這是因為 「bcd」 是 separator
中符合 實例中分隔符的第一個分隔符。 如果分隔符的順序反轉,因此第一個元素是 “bc”,而第二個元素是 “bcd”,則結果會是 “a” 和 “def”。
效能考慮
Split 方法會配置傳回數位物件的記憶體,以及每個數位元素的 String 物件。 如果您的應用程式需要最佳效能,或管理記憶體配置在應用程式中很重要,請考慮使用 IndexOf 或 IndexOfAny 方法,以及選擇性地使用 Compare 方法,在字串中尋找子字串串。
如果您要在分隔字元分割字串,請使用 IndexOf 或 IndexOfAny 方法來找出字串中的分隔字元。 如果您要在分隔符字串分割字串,請使用 IndexOf 或 IndexOfAny 方法來找出分隔符字串的第一個字元。 然後使用 Compare 方法來判斷該第一個字元後面的字元是否等於分隔符字串的其餘字元。
此外,如果使用相同的字元集來分割多個 Split 方法呼叫中的字元串,請考慮在每個方法呼叫中建立單一數位並參考它。 這可大幅減少每個方法呼叫的額外額外負荷。
給呼叫者的注意事項
在 .NET Framework 3.5 和舊版中,如果傳遞 Split(Char[]) 方法的 separator
null
或不包含任何字元,則方法會使用稍微不同的空格符集來分割字符串,而不是 Trim(Char[]) 方法來修剪字串。 從 .NET Framework 4 開始,這兩種方法都會使用相同的 Unicode 空格符集。
適用於
Split(Char[], StringSplitOptions)
根據指定的分隔字元和選項,將字串分割成子字串。
public:
cli::array <System::String ^> ^ Split(cli::array <char> ^ separator, StringSplitOptions options);
public string[] Split (char[] separator, StringSplitOptions options);
public string[] Split (char[]? separator, StringSplitOptions options);
[System.Runtime.InteropServices.ComVisible(false)]
public string[] Split (char[] separator, StringSplitOptions options);
member this.Split : char[] * StringSplitOptions -> string[]
[<System.Runtime.InteropServices.ComVisible(false)>]
member this.Split : char[] * StringSplitOptions -> string[]
Public Function Split (separator As Char(), options As StringSplitOptions) As String()
參數
- separator
- Char[]
此字串中分隔子字串的字元陣列、不含分隔符的空陣列,或 null
。
- options
- StringSplitOptions
列舉值的位元組合,指定是否要修剪子字串並包含空子字串。
傳回
陣列,其專案包含此字串中的子字串,並以 separator
中的一或多個字元分隔。 如需詳細資訊,請參閱一節。
- 屬性
例外狀況
options
不是其中一個 StringSplitOptions 值。
範例
下列範例會使用 StringSplitOptions 列舉來包含或排除 Split 方法所產生的子字串。
// This example demonstrates the String.Split(Char[], Boolean) and
// String.Split(Char[], Int32, Boolean) methods
using namespace System;
void Show( array<String^>^entries )
{
Console::WriteLine( "The return value contains these {0} elements:", entries->Length );
System::Collections::IEnumerator^ myEnum = entries->GetEnumerator();
while ( myEnum->MoveNext() )
{
String^ entry = safe_cast<String^>(myEnum->Current);
Console::Write( "<{0}>", entry );
}
Console::Write( "{0}{0}", Environment::NewLine );
}
int main()
{
String^ s = ",one,,,two,,,,,three,,";
array<Char>^sep = gcnew array<Char>{
','
};
array<String^>^result;
//
Console::WriteLine( "The original string is \"{0}\".", s );
Console::WriteLine( "The separation character is '{0}'.", sep[ 0 ] );
Console::WriteLine();
//
Console::WriteLine( "Split the string and return all elements:" );
result = s->Split( sep, StringSplitOptions::None );
Show( result );
//
Console::WriteLine( "Split the string and return all non-empty elements:" );
result = s->Split( sep, StringSplitOptions::RemoveEmptyEntries );
Show( result );
//
Console::WriteLine( "Split the string and return 2 elements:" );
result = s->Split( sep, 2, StringSplitOptions::None );
Show( result );
//
Console::WriteLine( "Split the string and return 2 non-empty elements:" );
result = s->Split( sep, 2, StringSplitOptions::RemoveEmptyEntries );
Show( result );
}
/*
This example produces the following results:
The original string is ",one,,,two,,,,,three,,".
The separation character is ','.
Split the string and return all elements:
The return value contains these 12 elements:
<><one><><><two><><><><><three><><>
Split the string and return all non-empty elements:
The return value contains these 3 elements:
<one><two><three>
Split the string and return 2 elements:
The return value contains these 2 elements:
<><one,,,two,,,,,three,,>
Split the string and return 2 non-empty elements:
The return value contains these 2 elements:
<one><,,two,,,,,three,,>
*/
// This example demonstrates the String.Split() methods that use
// the StringSplitOptions enumeration.
// Example 1: Split a string delimited by characters
Console.WriteLine("1) Split a string delimited by characters:\n");
string s1 = ",ONE,, TWO,, , THREE,,";
char[] charSeparators = new char[] { ',' };
string[] result;
Console.WriteLine($"The original string is: \"{s1}\".");
Console.WriteLine($"The delimiter character is: '{charSeparators[0]}'.\n");
// Split the string and return all elements
Console.WriteLine("1a) Return all elements:");
result = s1.Split(charSeparators, StringSplitOptions.None);
Show(result);
// Split the string and return all elements with whitespace trimmed
Console.WriteLine("1b) Return all elements with whitespace trimmed:");
result = s1.Split(charSeparators, StringSplitOptions.TrimEntries);
Show(result);
// Split the string and return all non-empty elements
Console.WriteLine("1c) Return all non-empty elements:");
result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// Split the string and return all non-whitespace elements with whitespace trimmed
Console.WriteLine("1d) Return all non-whitespace elements with whitespace trimmed:");
result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
Show(result);
// Split the string into only two elements, keeping the remainder in the last match
Console.WriteLine("1e) Split into only two elements:");
result = s1.Split(charSeparators, 2, StringSplitOptions.None);
Show(result);
// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("1f) Split into only two elements with whitespace trimmed:");
result = s1.Split(charSeparators, 2, StringSplitOptions.TrimEntries);
Show(result);
// Split the string into only two non-empty elements, keeping the remainder in the last match
Console.WriteLine("1g) Split into only two non-empty elements:");
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("1h) Split into only two non-whitespace elements with whitespace trimmed:");
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
Show(result);
// Example 2: Split a string delimited by another string
Console.WriteLine("2) Split a string delimited by another string:\n");
string s2 = "[stop]" +
"ONE[stop] [stop]" +
"TWO [stop][stop] [stop]" +
"THREE[stop][stop] ";
string[] stringSeparators = new string[] { "[stop]" };
Console.WriteLine($"The original string is: \"{s2}\".");
Console.WriteLine($"The delimiter string is: \"{stringSeparators[0]}\".\n");
// Split the string and return all elements
Console.WriteLine("2a) Return all elements:");
result = s2.Split(stringSeparators, StringSplitOptions.None);
Show(result);
// Split the string and return all elements with whitespace trimmed
Console.WriteLine("2b) Return all elements with whitespace trimmed:");
result = s2.Split(stringSeparators, StringSplitOptions.TrimEntries);
Show(result);
// Split the string and return all non-empty elements
Console.WriteLine("2c) Return all non-empty elements:");
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// Split the string and return all non-whitespace elements with whitespace trimmed
Console.WriteLine("2d) Return all non-whitespace elements with whitespace trimmed:");
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
Show(result);
// Split the string into only two elements, keeping the remainder in the last match
Console.WriteLine("2e) Split into only two elements:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.None);
Show(result);
// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("2f) Split into only two elements with whitespace trimmed:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.TrimEntries);
Show(result);
// Split the string into only two non-empty elements, keeping the remainder in the last match
Console.WriteLine("2g) Split into only two non-empty elements:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("2h) Split into only two non-whitespace elements with whitespace trimmed:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
Show(result);
// Display the array of separated strings using a local function
void Show(string[] entries)
{
Console.WriteLine($"The return value contains these {entries.Length} elements:");
foreach (string entry in entries)
{
Console.Write($"<{entry}>");
}
Console.Write("\n\n");
}
/*
This example produces the following results:
1) Split a string delimited by characters:
The original string is: ",ONE,, TWO,, , THREE,,".
The delimiter character is: ','.
1a) Return all elements:
The return value contains these 9 elements:
<><ONE><>< TWO><>< >< THREE><><>
1b) Return all elements with whitespace trimmed:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>
1c) Return all non-empty elements:
The return value contains these 4 elements:
<ONE>< TWO>< >< THREE>
1d) Return all non-whitespace elements with whitespace trimmed:
The return value contains these 3 elements:
<ONE><TWO><THREE>
1e) Split into only two elements:
The return value contains these 2 elements:
<><ONE,, TWO,, , THREE,,>
1f) Split into only two elements with whitespace trimmed:
The return value contains these 2 elements:
<><ONE,, TWO,, , THREE,,>
1g) Split into only two non-empty elements:
The return value contains these 2 elements:
<ONE>< TWO,, , THREE,,>
1h) Split into only two non-whitespace elements with whitespace trimmed:
The return value contains these 2 elements:
<ONE><TWO,, , THREE,,>
2) Split a string delimited by another string:
The original string is: "[stop]ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] ".
The delimiter string is: "[stop]".
2a) Return all elements:
The return value contains these 9 elements:
<><ONE>< ><TWO ><>< ><THREE><>< >
2b) Return all elements with whitespace trimmed:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>
2c) Return all non-empty elements:
The return value contains these 6 elements:
<ONE>< ><TWO >< ><THREE>< >
2d) Return all non-whitespace elements with whitespace trimmed:
The return value contains these 3 elements:
<ONE><TWO><THREE>
2e) Split into only two elements:
The return value contains these 2 elements:
<><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] >
2f) Split into only two elements with whitespace trimmed:
The return value contains these 2 elements:
<><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop]>
2g) Split into only two non-empty elements:
The return value contains these 2 elements:
<ONE>< [stop]TWO [stop][stop] [stop]THREE[stop][stop] >
2h) Split into only two non-whitespace elements with whitespace trimmed:
The return value contains these 2 elements:
<ONE><TWO [stop][stop] [stop]THREE[stop][stop]>
*/
// This example demonstrates the String.Split() methods that use
// the StringSplitOptions enumeration.
// Display the array of separated strings using a local function
let show (entries: string[]) =
printfn $"The return value contains these {entries.Length} elements:"
for entry in entries do
printf $"<{entry}>"
printf "\n\n"
// Example 1: Split a string delimited by characters
printfn "1) Split a string delimited by characters:\n"
let s1 = ",ONE,, TWO,, , THREE,,"
let charSeparators = [| ',' |]
printfn $"The original string is: \"{s1}\"."
printfn $"The delimiter character is: '{charSeparators[0]}'.\n"
// Split the string and return all elements
printfn "1a) Return all elements:"
let result = s1.Split(charSeparators, StringSplitOptions.None)
show result
// Split the string and return all elements with whitespace trimmed
printfn "1b) Return all elements with whitespace trimmed:"
let result = s1.Split(charSeparators, StringSplitOptions.TrimEntries)
show result
// Split the string and return all non-empty elements
printfn "1c) Return all non-empty elements:"
let result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries)
show result
// Split the string and return all non-whitespace elements with whitespace trimmed
printfn "1d) Return all non-whitespace elements with whitespace trimmed:"
let result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)
show result
// Split the string into only two elements, keeping the remainder in the last match
printfn "1e) Split into only two elements:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.None)
show result
// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
printfn "1f) Split into only two elements with whitespace trimmed:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.TrimEntries)
show result
// Split the string into only two non-empty elements, keeping the remainder in the last match
printfn "1g) Split into only two non-empty elements:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
show result
// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
printfn "1h) Split into only two non-whitespace elements with whitespace trimmed:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)
show result
// Example 2: Split a string delimited by another string
printfn "2) Split a string delimited by another string:\n"
let s2 = "[stop]" +
"ONE[stop] [stop]" +
"TWO [stop][stop] [stop]" +
"THREE[stop][stop] "
let stringSeparators = [| "[stop]" |]
printfn $"The original string is: \"{s2}\"."
printfn $"The delimiter string is: \"{stringSeparators[0]}\".\n"
// Split the string and return all elements
printfn "2a) Return all elements:"
let result = s2.Split(stringSeparators, StringSplitOptions.None)
show result
// Split the string and return all elements with whitespace trimmed
printfn "2b) Return all elements with whitespace trimmed:"
let result = s2.Split(stringSeparators, StringSplitOptions.TrimEntries)
show result
// Split the string and return all non-empty elements
printfn "2c) Return all non-empty elements:"
let result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)
show result
// Split the string and return all non-whitespace elements with whitespace trimmed
printfn "2d) Return all non-whitespace elements with whitespace trimmed:"
let result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)
show result
// Split the string into only two elements, keeping the remainder in the last match
printfn "2e) Split into only two elements:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.None)
show result
// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
printfn "2f) Split into only two elements with whitespace trimmed:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.TrimEntries)
show result
// Split the string into only two non-empty elements, keeping the remainder in the last match
printfn "2g) Split into only two non-empty elements:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
show result
// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
printfn "2h) Split into only two non-whitespace elements with whitespace trimmed:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)
show result
(*
This example produces the following results:
1) Split a string delimited by characters:
The original string is: ",ONE,, TWO,, , THREE,,".
The delimiter character is: ','.
1a) Return all elements:
The return value contains these 9 elements:
<><ONE><>< TWO><>< >< THREE><><>
1b) Return all elements with whitespace trimmed:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>
1c) Return all non-empty elements:
The return value contains these 4 elements:
<ONE>< TWO>< >< THREE>
1d) Return all non-whitespace elements with whitespace trimmed:
The return value contains these 3 elements:
<ONE><TWO><THREE>
1e) Split into only two elements:
The return value contains these 2 elements:
<><ONE,, TWO,, , THREE,,>
1f) Split into only two elements with whitespace trimmed:
The return value contains these 2 elements:
<><ONE,, TWO,, , THREE,,>
1g) Split into only two non-empty elements:
The return value contains these 2 elements:
<ONE>< TWO,, , THREE,,>
1h) Split into only two non-whitespace elements with whitespace trimmed:
The return value contains these 2 elements:
<ONE><TWO,, , THREE,,>
2) Split a string delimited by another string:
The original string is: "[stop]ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] ".
The delimiter string is: "[stop]".
2a) Return all elements:
The return value contains these 9 elements:
<><ONE>< ><TWO ><>< ><THREE><>< >
2b) Return all elements with whitespace trimmed:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>
2c) Return all non-empty elements:
The return value contains these 6 elements:
<ONE>< ><TWO >< ><THREE>< >
2d) Return all non-whitespace elements with whitespace trimmed:
The return value contains these 3 elements:
<ONE><TWO><THREE>
2e) Split into only two elements:
The return value contains these 2 elements:
<><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] >
2f) Split into only two elements with whitespace trimmed:
The return value contains these 2 elements:
<><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop]>
2g) Split into only two non-empty elements:
The return value contains these 2 elements:
<ONE>< [stop]TWO [stop][stop] [stop]THREE[stop][stop] >
2h) Split into only two non-whitespace elements with whitespace trimmed:
The return value contains these 2 elements:
<ONE><TWO [stop][stop] [stop]THREE[stop][stop]>
*)
Public Shared Sub StringSplitOptionsExamples()
' This example demonstrates the String.Split() methods that use
' the StringSplitOptions enumeration.
' Example 1: Split a string delimited by characters
Console.WriteLine("1) Split a string delimited by characters:" & vbCrLf)
Dim s1 As String = ",ONE,, TWO,, , THREE,,"
Dim charSeparators() As Char = {","c}
Dim result() As String
Console.WriteLine("The original string is: ""{0}"".", s1)
Console.WriteLine("The delimiter character is: '{0}'." & vbCrLf, charSeparators(0))
' Split the string and return all elements
Console.WriteLine("1a) Return all elements:")
result = s1.Split(charSeparators, StringSplitOptions.None)
Show(result)
' Split the string and return all elements with whitespace trimmed
Console.WriteLine("1b) Return all elements with whitespace trimmed:")
result = s1.Split(charSeparators, StringSplitOptions.TrimEntries)
Show(result)
' Split the string and return all non-empty elements
Console.WriteLine("1c) Return all non-empty elements:")
result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries)
Show(result)
' Split the string and return all non-whitespace elements with whitespace trimmed
Console.WriteLine("1d) Return all non-whitespace elements with whitespace trimmed:")
result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries)
Show(result)
' Split the string into only two elements, keeping the remainder in the last match
Console.WriteLine("1e) Split into only two elements:")
result = s1.Split(charSeparators, 2, StringSplitOptions.None)
Show(result)
' Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("1f) Split into only two elements with whitespace trimmed:")
result = s1.Split(charSeparators, 2, StringSplitOptions.TrimEntries)
Show(result)
' Split the string into only two non-empty elements, keeping the remainder in the last match
Console.WriteLine("1g) Split into only two non-empty elements:")
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
Show(result)
' Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("1h) Split into only two non-whitespace elements with whitespace trimmed:")
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries)
Show(result)
' Example 2: Split a string delimited by another string
Console.WriteLine("2) Split a string delimited by another string:" & vbCrLf)
Dim s2 As String = "[stop]" +
"ONE[stop] [stop]" +
"TWO [stop][stop] [stop]" +
"THREE[stop][stop] "
Dim stringSeparators() As String = {"[stop]"}
Console.WriteLine("The original string is: ""{0}"".", s2)
Console.WriteLine("The delimiter string is: ""{0}""." & vbCrLf, stringSeparators(0))
' Split the string and return all elements
Console.WriteLine("2a) Return all elements:")
result = s2.Split(stringSeparators, StringSplitOptions.None)
Show(result)
' Split the string and return all elements with whitespace trimmed
Console.WriteLine("2b) Return all elements with whitespace trimmed:")
result = s2.Split(stringSeparators, StringSplitOptions.TrimEntries)
Show(result)
' Split the string and return all non-empty elements
Console.WriteLine("2c) Return all non-empty elements:")
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)
Show(result)
' Split the string and return all non-whitespace elements with whitespace trimmed
Console.WriteLine("2d) Return all non-whitespace elements with whitespace trimmed:")
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries)
Show(result)
' Split the string into only two elements, keeping the remainder in the last match
Console.WriteLine("2e) Split into only two elements:")
result = s2.Split(stringSeparators, 2, StringSplitOptions.None)
Show(result)
' Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("2f) Split into only two elements with whitespace trimmed:")
result = s2.Split(stringSeparators, 2, StringSplitOptions.TrimEntries)
Show(result)
' Split the string into only two non-empty elements, keeping the remainder in the last match
Console.WriteLine("2g) Split into only two non-empty elements:")
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
Show(result)
' Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("2h) Split into only two non-whitespace elements with whitespace trimmed:")
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries)
Show(result)
End Sub
' Display the array of separated strings.
Public Shared Sub Show(ByVal entries() As String)
Console.WriteLine("The return value contains these {0} elements:", entries.Length)
Dim entry As String
For Each entry In entries
Console.Write("<{0}>", entry)
Next entry
Console.Write(vbCrLf & vbCrLf)
End Sub
'This example produces the following results:
'
' 1) Split a string delimited by characters:
'
' The original string is: ",ONE,, TWO,, , THREE,,".
' The delimiter character is: ','.
'
' 1a) Return all elements:
' The return value contains these 9 elements:
' <><ONE><>< TWO><>< >< THREE><><>
'
' 1b) Return all elements with whitespace trimmed:
' The return value contains these 9 elements:
' <><ONE><><TWO><><><THREE><><>
'
' 1c) Return all non-empty elements:
' The return value contains these 4 elements:
' <ONE>< TWO>< >< THREE>
'
' 1d) Return all non-whitespace elements with whitespace trimmed:
' The return value contains these 3 elements:
' <ONE><TWO><THREE>
'
' 1e) Split into only two elements:
' The return value contains these 2 elements:
' <><ONE,, TWO,, , THREE,,>
'
' 1f) Split into only two elements with whitespace trimmed:
' The return value contains these 2 elements:
' <><ONE,, TWO,, , THREE,,>
'
' 1g) Split into only two non-empty elements:
' The return value contains these 2 elements:
' <ONE>< TWO,, , THREE,,>
'
' 1h) Split into only two non-whitespace elements with whitespace trimmed:
' The return value contains these 2 elements:
' <ONE><TWO,, , THREE,,>
'
' 2) Split a string delimited by another string:
'
' The original string is: "[stop]ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] ".
' The delimiter string is: "[stop]".
'
' 2a) Return all elements:
' The return value contains these 9 elements:
' <><ONE>< ><TWO ><>< ><THREE><>< >
'
' 2b) Return all elements with whitespace trimmed:
' The return value contains these 9 elements:
' <><ONE><><TWO><><><THREE><><>
'
' 2c) Return all non-empty elements:
' The return value contains these 6 elements:
' <ONE>< ><TWO >< ><THREE>< >
'
' 2d) Return all non-whitespace elements with whitespace trimmed:
' The return value contains these 3 elements:
' <ONE><TWO><THREE>
'
' 2e) Split into only two elements:
' The return value contains these 2 elements:
' <><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] >
'
' 2f) Split into only two elements with whitespace trimmed:
' The return value contains these 2 elements:
' <><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop]>
'
' 2g) Split into only two non-empty elements:
' The return value contains these 2 elements:
' <ONE>< [stop]TWO [stop][stop] [stop]THREE[stop][stop] >
'
' 2h) Split into only two non-whitespace elements with whitespace trimmed:
' The return value contains these 2 elements:
' <ONE><TWO [stop][stop] [stop]THREE[stop][stop]>
'
備註
分隔符(separator
陣列中的字元)不包含在傳回陣列的元素中。 例如,如果 separator
陣列包含字元 「-」 且目前字串實例的值是 「aa-bb-cc」,則方法會傳回包含三個元素的陣列:「aa」。、“bb”和 “cc”。
如果這個實例不包含 separator
中的任何字元,則傳回的陣列是由包含這個實例的單一元素所組成。
如果 options
參數 RemoveEmptyEntries 且這個實例的長度為零,則方法會傳回空陣列。
separator
的每個元素都會定義由單一字元組成的個別分隔符。 如果 options
自變數是 None,而兩個分隔符是相鄰的,或是在這個實例的開頭或結尾找到分隔符,對應的陣列元素會包含 String.Empty。 例如,如果 separator
包含兩個元素,'-'
和 '_'
,則字串實例的值是 “-_aa-_”,而且 options
自變數的值是 None,此方法會傳回具有下列五個元素的字符串陣列:
String.Empty,代表索引0上“-” 字元前面的空字串。
String.Empty,代表索引 0 上 “-” 字元與索引 1 上 “_” 字元之間的空字串。
“aa”。
String.Empty,代表索引 4 上 “-” 字元後面的空字串。
String.Empty,代表索引 5 上 “_” 字元後面的空字串。
分隔符陣列
如果 separator
參數是 null
或不包含任何字元,則空格符會假設為分隔符。 空格符是由 Unicode 標準所定義,Char.IsWhiteSpace 方法會傳回 true
傳遞至該字元。
若要傳遞 char[] separator
參數的 null
,您必須指出 null
的類型,以釐清呼叫與其他多載,例如 Split(String[], StringSplitOptions)。 下列範例示範數種方式來明確識別此多載。
string phrase = "The quick brown fox";
_ = phrase.Split(default(char[]), StringSplitOptions.RemoveEmptyEntries);
_ = phrase.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries);
_ = phrase.Split(null as char[], StringSplitOptions.RemoveEmptyEntries);
let phrase = "The quick brown fox"
phrase.Split(Unchecked.defaultof<char[]>, StringSplitOptions.RemoveEmptyEntries) |> ignore
phrase.Split(null :> char[], StringSplitOptions.RemoveEmptyEntries) |> ignore
phrase.Split((null: char[]), StringSplitOptions.RemoveEmptyEntries) |> ignore
Dim phrase As String = "The quick brown fox"
Dim words() As String
words = phrase.Split(TryCast(Nothing, Char()),
StringSplitOptions.RemoveEmptyEntries)
words = phrase.Split(New Char() {},
StringSplitOptions.RemoveEmptyEntries)
比較詳細數據
Split 方法會擷取此字串中的子字串,此字串是以 separator
參數中的一或多個字元分隔,並傳回這些子字元串做為陣列的元素。
Split 方法會使用區分大小寫的序數排序規則來執行比較來尋找分隔符。 如需單字、字串和序數排序的詳細資訊,請參閱 System.Globalization.CompareOptions 列舉。
效能考慮
Split 方法會配置傳回數位物件的記憶體,以及每個數位元素的 String 物件。 如果您的應用程式需要最佳效能,或管理記憶體配置在應用程式中很重要,請考慮使用 IndexOf 或 IndexOfAny 方法,以及選擇性地使用 Compare 方法,在字串中尋找子字串串。
如果您要在分隔字元分割字串,請使用 IndexOf 或 IndexOfAny 方法來找出字串中的分隔字元。 如果您要在分隔符字串分割字串,請使用 IndexOf 或 IndexOfAny 方法來找出分隔符字串的第一個字元。 然後使用 Compare 方法來判斷該第一個字元後面的字元是否等於分隔符字串的其餘字元。
此外,如果使用相同的字元集來分割多個 Split 方法呼叫中的字元串,請考慮在每個方法呼叫中建立單一數位並參考它。 這可大幅減少每個方法呼叫的額外額外負荷。
給呼叫者的注意事項
在 .NET Framework 3.5 和舊版中,如果傳遞 Split(Char[]) 方法的 separator
null
或不包含任何字元,則方法會使用稍微不同的空格符集來分割字符串,而不是 Trim(Char[]) 方法來修剪字串。 從 .NET Framework 4 開始,這兩種方法都會使用相同的 Unicode 空格符集。