String.Split String.Split String.Split String.Split Method

定義

傳回字串陣列,這個陣列包含這個執行個體中,由指定的字串或 Unicode 字元陣列之項目所分隔的子字串。Returns a string array that contains the substrings in this instance that are delimited by elements of a specified string or Unicode character array.

多載

Split(Char[], Int32, StringSplitOptions) Split(Char[], Int32, StringSplitOptions) Split(Char[], Int32, StringSplitOptions) Split(Char[], Int32, StringSplitOptions)

根據陣列中的字元分割字串成最大數目的子字串。Splits a string into a maximum number of substrings based on the characters in an array.

Split(Char, Int32, StringSplitOptions) Split(Char, Int32, StringSplitOptions) Split(Char, Int32, StringSplitOptions)
Split(String[], Int32, StringSplitOptions) Split(String[], Int32, StringSplitOptions) Split(String[], Int32, StringSplitOptions) Split(String[], Int32, StringSplitOptions)

根據陣列中的字串分割字串成最大數目的子字串。Splits a string into a maximum number of substrings based on the strings in an array. 您可以指定子字串是否包含空的陣列元素。You can specify whether the substrings include empty array elements.

Split(String[], StringSplitOptions) Split(String[], StringSplitOptions) Split(String[], StringSplitOptions) Split(String[], StringSplitOptions)

根據陣列中的字串分割字串成子字串。Splits a string into substrings based on the strings in an array. 您可以指定子字串是否包含空的陣列元素。You can specify whether the substrings include empty array elements.

Split(String, Int32, StringSplitOptions) Split(String, Int32, StringSplitOptions) Split(String, Int32, StringSplitOptions)
Split(Char[], StringSplitOptions) Split(Char[], StringSplitOptions) Split(Char[], StringSplitOptions) Split(Char[], StringSplitOptions)

根據陣列中的字元分割字串成子字串。Splits a string into substrings based on the characters in an array. 您可以指定子字串是否包含空的陣列元素。You can specify whether the substrings include empty array elements.

Split(Char[], Int32) Split(Char[], Int32) Split(Char[], Int32) Split(Char[], Int32)

根據陣列中的字元分割字串成最大數目的子字串。Splits a string into a maximum number of substrings based on the characters in an array. 您也要指定傳回的子字串之最大數目。You also specify the maximum number of substrings to return.

Split(Char, StringSplitOptions) Split(Char, StringSplitOptions) Split(Char, StringSplitOptions)
Split(String, StringSplitOptions) Split(String, StringSplitOptions) Split(String, StringSplitOptions)
Split(Char[]) Split(Char[]) Split(Char[]) Split(Char[])

根據陣列中的字元分割字串成子字串。Splits a string into substrings that are based on the characters in an array.

備註

Split用來將分隔的字串分割成子字串。Split is used to break a delimited string into substrings. 您可以使用字元陣列指定零個、一個或多個分隔字元( Split(Char[])方法),也可以使用字元陣列來指定零個、一個或多個分隔字串。You can use either a character array to specify zero, one, or multiple delimiting characters (the Split(Char[]) method), or you can use a character array to specify zero, one, or multiple delimiting strings. 方法的多載可讓您限制方法Split(Char[], Int32) (方法)所傳回的子字串數目,以判斷傳回Split(Char[], StringSplitOptions)的子字串是否包含空字串(和Split(String[], StringSplitOptions)方法,或Split若要同時執行這Split(Char[], Int32, StringSplitOptions)Split(String[], Int32, StringSplitOptions)個(和方法)。Overloads of the Split method allow you to limit the number of substrings returned by the method (the Split(Char[], Int32) method), to determine whether empty strings are included in the returned substrings (the Split(Char[], StringSplitOptions) and Split(String[], StringSplitOptions) methods, or to do both (the Split(Char[], Int32, StringSplitOptions) and Split(String[], Int32, StringSplitOptions) methods).

注意

本文中的 C# 範例會在 Try.NET 內嵌程式碼執行器和測試區執行。The C# examples in this article run in the Try.NET inline code runner and playground. 選取 [執行] 按鈕以在互動式視窗中執行範例。Select the Run button to run an example in an interactive window. 執行程式碼之後,您便可以修改它,並再選取一次 [執行] 來執行修改過的程式碼。Once you execute the code, you can modify it and run the modified code by selecting Run again. 修改過的程式碼會在互動式視窗中執行,或是如果編譯失敗的話,互動式視窗會顯示所有 C# 編譯器錯誤訊息。The modified code either runs in the interactive window or, if compilation fails, the interactive window displays all C# compiler error messages.

String. Split 的替代專案Alternatives to String.Split

Split方法不一定是將分隔字串分割成子字串的最佳方式。The Split method is not always the best way to break a delimited string into substrings. 如果您不想要解壓縮分隔字串的所有子字串,或如果您想要根據模式來剖析字串,而不是一組分隔符號,請考慮下列替代方式。If you don't want to extract all of the substrings of a delimited string, or if you want to parse a string based on a pattern instead of a set of delimiter characters, consider the following alternatives.

規則運算式Regular expressions

如果您的字串符合固定模式,您可以使用正則運算式來解壓縮和處理其元素。If your strings conform to a fixed pattern, you can use a regular expression to extract and handle their elements. 例如,如果字串採用「數位運算元數位」格式,您就可以使用正則運算式來解壓縮和處理字串的元素。For example, if strings take the form "number operand number" you can use a regular expression to extract and handle the string's elements. 以下為範例:Here's an example:

   String[] expressions = { "16 + 21", "31 * 3", "28 / 3",
                            "42 - 18", "12 * 7",
                            "2, 4, 6, 8" };
   String pattern = @"(\d+)\s+([-+*/])\s+(\d+)";
   foreach (var expression in expressions)
      foreach (System.Text.RegularExpressions.Match m in 
      System.Text.RegularExpressions.Regex.Matches(expression, pattern)) {
         int value1 = Int32.Parse(m.Groups[1].Value);
         int value2 = Int32.Parse(m.Groups[3].Value);
         switch (m.Groups[2].Value)
         {
            case "+":
               Console.WriteLine("{0} = {1}", m.Value, value1 + value2);
               break;
            case "-":
               Console.WriteLine("{0} = {1}", m.Value, value1 - value2);
               break;
            case "*":
               Console.WriteLine("{0} = {1}", m.Value, value1 * value2);
               break;
            case "/":
               Console.WriteLine("{0} = {1:N2}", m.Value, value1 / value2);
               break;
         }
      }
// The example displays the following output:
//       16 + 21 = 37
//       31 * 3 = 93
//       28 / 3 = 9.33
//       42 - 18 = 24
//       12 * 7 = 84
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim expressions() As String = { "16 + 21", "31 * 3", "28 / 3",
                                      "42 - 18", "12 * 7",
                                      "2, 4, 6, 8" }

      Dim pattern As String = "(\d+)\s+([-+*/])\s+(\d+)"
      For Each expression In expressions
         For Each m As Match in Regex.Matches(expression, pattern)
            Dim value1 As Integer = Int32.Parse(m.Groups(1).Value)
            Dim value2 As Integer = Int32.Parse(m.Groups(3).Value)
            Select Case m.Groups(2).Value
               Case "+"
                  Console.WriteLine("{0} = {1}", m.Value, value1 + value2)
               Case "-"
                  Console.WriteLine("{0} = {1}", m.Value, value1 - value2)
               Case "*"
                  Console.WriteLine("{0} = {1}", m.Value, value1 * value2)
               Case "/"
                  Console.WriteLine("{0} = {1:N2}", m.Value, value1 / value2)
            End Select
         Next
      Next
   End Sub
End Module
' The example displays the following output:
'       16 + 21 = 37
'       31 * 3 = 93
'       28 / 3 = 9.33
'       42 - 18 = 24
'       12 * 7 = 84

正則運算式模式(\d+)\s+([-+*/])\s+(\d+)的定義如下:The regular expression pattern (\d+)\s+([-+*/])\s+(\d+) is defined like this:

模式Pattern 說明Description
(\d+) 比對一個或多個十進位數字。Match one or more decimal digits. 這是第一個擷取群組。This is the first capturing group.
\s+ 比對一個或多個空白字元。Match one or more white-space characters.
([-+*/]) 符合算術運算子正負號(+、-、* 或/)。Match an arithmetic operator sign (+, -, *, or /). 這是第二個擷取群組。This is the second capturing group.
\s+ 比對一個或多個空白字元。Match one or more white-space characters.
(\d+) 比對一個或多個十進位數字。Match one or more decimal digits. 這是第三個擷取群組。This is the third capturing group.

您也可以使用正則運算式,根據模式(而非一組固定的字元)從字串中解壓縮子字串。You can also use a regular expression to extract substrings from a string based on a pattern rather than a fixed set of characters. 這是發生上述其中一種情況的常見案例:This is a common scenario when either of these conditions occurs:

  • 一或多個分隔符號不一定會作為String實例中的分隔符號。One or more of the delimiter characters does not always serve as a delimiter in the String instance.

  • 分隔字元的順序和數目是變數或未知的。The sequence and number of delimiter characters is variable or unknown.

例如, Split方法無法用來分割下列字串,因為\n (在中C#)或vbCrLf (Visual Basic)字元中的數位是可變的,而且不一定會作為分隔符號。For example, the Split method cannot be used to split the following string, because the number of \n (in C#) or vbCrLf (in Visual Basic) characters is variable, and they don't always serve as delimiters.

[This is captured\ntext.]\n\n[\n[This is more captured text.]\n]  
\n[Some more captured text:\n   Option1\n   Option2][Terse text.]  

正則運算式可以輕鬆地分割此字串,如下列範例所示。A regular expression can split this string easily, as the following example shows.

String input = "[This is captured\ntext.]\n\n[\n" +
               "[This is more captured text.]\n]\n" +
               "[Some more captured text:\n   Option1" +
               "\n   Option2][Terse text.]";
String pattern = @"\[([^\[\]]+)\]";
int ctr = 0;
foreach (System.Text.RegularExpressions.Match m in 
   System.Text.RegularExpressions.Regex.Matches(input, pattern))
   Console.WriteLine("{0}: {1}", ++ctr, m.Groups[1].Value);
// The example displays the following output:
//       1: This is captured
//       text.
//       2: This is more captured text.
//       3: Some more captured text:
//          Option1
//          Option2
//       4: Terse text.
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim input As String = String.Format("[This is captured{0}text.]" +
                                          "{0}{0}[{0}[This is more " +
                                          "captured text.]{0}{0}" +
                                          "[Some more captured text:" +
                                          "{0}   Option1" +
                                          "{0}   Option2][Terse text.]",
                                          vbCrLf)
      Dim pattern As String = "\[([^\[\]]+)\]"
      Dim ctr As Integer = 0
      For Each m As Match In Regex.Matches(input, pattern)
         ctr += 1
         Console.WriteLine("{0}: {1}", ctr, m.Groups(1).Value)
      Next
   End Sub
End Module
' The example displays the following output:
'       1: This is captured
'       text.
'       2: This is more captured text.
'       3: Some more captured text:
'          Option1
'          Option2
'       4: Terse text.

正則運算式模式\[([^\[\]]+)\]的定義如下:The regular expression pattern \[([^\[\]]+)\] is defined like this:

模式Pattern 說明Description
\[ 比對左括弧。Match an opening bracket.
([^\[\]]+) 比對不是左或右方括弧的任何字元一次或多次。Match any character that is not an opening or a closing bracket one or more times. 這是第一個擷取群組。This is the first capturing group.
\] 符合右括弧。Match a closing bracket.

方法幾乎與String.Split完全相同,不同之處在于它會根據正則運算式模式(而非固定字元集)分割字串。 Regex.SplitThe Regex.Split method is almost identical to String.Split, except that it splits a string based on a regular expression pattern instead of a fixed character set. 例如,下列範例會使用Regex.Split方法來分割字串,其中包含以不同的連字號和其他字元組合分隔的子字串。For example, the following example uses the Regex.Split method to split a string that contains substrings delimited by various combinations of hyphens and other characters.

String input = "abacus -- alabaster - * - atrium -+- " +
               "any -*- actual - + - armoire - - alarm";
String pattern = @"\s-\s?[+*]?\s?-\s";
String[] elements = System.Text.RegularExpressions.Regex.Split(input, pattern);
foreach (var element in elements)
   Console.WriteLine(element);

// The example displays the following output:
//       abacus
//       alabaster
//       atrium
//       any
//       actual
//       armoire
//       alarm
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim input As String = "abacus -- alabaster - * - atrium -+- " +
                            "any -*- actual - + - armoir - - alarm"
      Dim pattern As String = "\s-\s?[+*]?\s?-\s"
      Dim elements() As String = Regex.Split(input, pattern)
      For Each element In elements
         Console.WriteLine(element)
      Next
   End Sub
End Module
' The example displays the following output:
'       abacus
'       alabaster
'       atrium
'       any
'       actual
'       armoir
'       alarm

正則運算式模式\s-\s?[+*]?\s?-\s的定義如下:The regular expression pattern \s-\s?[+*]?\s?-\s is defined like this:

模式Pattern 說明Description
\s- 比對空白字元後面緊接著一個連字號的空白字元。Match a white-space character followed by a hyphen.
\s? 比對零個或一個空白字元。Match zero or one white-space character.
[+*]? 符合零或一次的 + 或 * 字元。Match zero or one occurrence of either the + or * character.
\s? 比對零個或一個空白字元。Match zero or one white-space character.
-\s 比對後面接著空白字元的連字號。Match a hyphen followed by a white-space character.

搜尋方法和 Substring 方法Search methods and the Substring method

如果您對字串中的所有子字串不感興趣,您可能會想要使用其中一個字串比較方法,以傳回符合項開始的索引。If you aren't interested in all of the substrings in a string, you might prefer to work with one of the string comparison methods that returns the index at which the match begins. 接著,您可以呼叫Substring方法來解壓縮您想要的子字串。You can then call the Substring method to extract the substring that you want. 字串比較方法包括:The string comparison methods include:

  • IndexOf,它會傳回字串實例中第一次出現的字元或字串之以零為起始的索引。IndexOf, which returns the zero-based index of the first occurrence of a character or string in a string instance.

  • IndexOfAny,它會傳回字元陣列中任何字元第一次出現時,在目前字串實例中以零為起始的索引。IndexOfAny, which returns the zero-based index in the current string instance of the first occurrence of any character in a character array.

  • LastIndexOf,它會傳回字串實例中最後一次出現的字元或字串之以零為起始的索引。LastIndexOf, which returns the zero-based index of the last occurrence of a character or string in a string instance.

  • LastIndexOfAny,它會在字元陣列中的任何字元最後一次出現時,傳回目前字串實例中以零為起始的索引。LastIndexOfAny, which returns a zero-based index in the current string instance of the last occurrence of any character in a character array.

下列範例會使用IndexOf方法,在字串中尋找句點。The following example uses the IndexOf method to find the periods in a string. 然後,它會Substring使用方法來傳回完整的句子。It then uses the Substring method to return full sentences.

String value = "This is the first sentence in a string. " +
               "More sentences will follow. For example, " +
               "this is the third sentence. This is the " +
               "fourth. And this is the fifth and final " +
               "sentence.";
var sentences = new List<String>();
int position = 0;
int start = 0;
// Extract sentences from the string.
do 
{
   position = value.IndexOf('.', start);
   if (position >= 0) 
   {
      sentences.Add(value.Substring(start, position - start + 1).Trim());
      start = position + 1;
   }
} while (position > 0);

// Display the sentences.
foreach (var sentence in sentences)
   Console.WriteLine(sentence);

// The example displays the following output:
//       This is the first sentence in a string.
//       More sentences will follow.
//       For example, this is the third sentence.
//       This is the fourth.
//       And this is the fifth and final sentence.
Imports System.Collections.Generic

Module Example
   Public Sub Main()
      Dim value As String = "This is the first sentence in a string. " +
                            "More sentences will follow. For example, " +
                            "this is the third sentence. This is the " +
                            "fourth. And this is the fifth and final " +
                            "sentence."
      Dim sentences As New List(Of String)
      Dim position As Integer = 0
      Dim start As Integer = 0
      ' Extract sentences from the string.
      Do
         position = value.IndexOf("."c, start)
         If position >= 0 Then
            sentences.Add(value.Substring(start, position - start + 1).Trim())
            start = position + 1
         End If
      Loop While position > 0
      
      ' Display the sentences.
      For Each sentence In sentences
         Console.WriteLine(sentence)
      Next
   End Sub
End Module
' The example displays the following output:
'       This is the first sentence in a string.
'       More sentences will follow.
'       For example, this is the third sentence.
'       This is the fourth.
'       And this is the fifth and final sentence.

Split(Char[], Int32, StringSplitOptions) Split(Char[], Int32, StringSplitOptions) Split(Char[], Int32, StringSplitOptions) Split(Char[], Int32, StringSplitOptions)

根據陣列中的字元分割字串成最大數目的子字串。Splits a string into a maximum number of substrings based on the characters in an array.

public:
 cli::array <System::String ^> ^ Split(cli::array <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[]
Public Function Split (separator As Char(), count As Integer, options As StringSplitOptions) As String()

參數

separator
Char[]

字串陣列 (可分隔這個字串中的子字串)、不含任何分隔符號的空陣列,或 nullA character array that delimits the substrings in this string, an empty array that contains no delimiters, or null.

count
Int32 Int32 Int32 Int32

要傳回的子字串之最大數目。The maximum number of substrings to return.

options
StringSplitOptions StringSplitOptions StringSplitOptions StringSplitOptions

RemoveEmptyEntries 表示要省略傳回陣列中的空陣列項目,否則 None 表示要包含傳回陣列中的空陣列項目。RemoveEmptyEntries to omit empty array elements from the array returned; or None to include empty array elements in the array returned.

傳回

String[]

陣列,其項目包含了這個字串中由 separator 內的一或多個字元所分隔的子字串。An array whose elements contain the substrings in this string that are delimited by one or more characters in separator. 如需詳細資訊,請參閱<備註>一節。For more information, see the Remarks section.

例外狀況

options 不是其中一個 StringSplitOptions 值。options is not one of the StringSplitOptions values.

範例

下列範例會使用StringSplitOptions列舉來包含或排除方法所Split產生的子字串。The following example uses the StringSplitOptions enumeration to include or exclude substrings generated by the Split method.

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

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

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

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

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

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

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

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

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

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

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

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

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

/*
This example produces the following results:

1) Split a string delimited by characters:

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

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

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

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

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

2) Split a string delimited by another string:

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

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

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

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

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

*/

' This example demonstrates the String() methods that use
' the StringSplitOptions enumeration.
Class Sample
    Public Shared Sub Main() 
        Dim s1 As String = ",ONE,,TWO,,,THREE,,"
        Dim s2 As String = "[stop]" & _
                           "ONE[stop][stop]" & _
                           "TWO[stop][stop][stop]" & _
                           "THREE[stop][stop]"
        Dim charSeparators() As Char = {","c}
        Dim stringSeparators() As String = {"[stop]"}
        Dim result() As String
        ' ------------------------------------------------------------------------------
        ' Split a string delimited by characters.
        ' ------------------------------------------------------------------------------
        Console.WriteLine("1) Split a string delimited by characters:" & vbCrLf)
        
        ' Display the original string and delimiter characters.
        Console.WriteLine("1a )The original string is ""{0}"".", s1)
        Console.WriteLine("The delimiter character is '{0}'." & vbCrLf, charSeparators(0))
        
        ' Split a string delimited by characters and return all elements.
        Console.WriteLine("1b) Split a string delimited by characters and " & _
                          "return all elements:")
        result = s1.Split(charSeparators, StringSplitOptions.None)
        Show(result)
        
        ' Split a string delimited by characters and return all non-empty elements.
        Console.WriteLine("1c) Split a string delimited by characters and " & _
                          "return all non-empty elements:")
        result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries)
        Show(result)
        
        ' Split the original string into the string and empty string before the 
        ' delimiter and the remainder of the original string after the delimiter.
        Console.WriteLine("1d) Split a string delimited by characters and " & _
                          "return 2 elements:")
        result = s1.Split(charSeparators, 2, StringSplitOptions.None)
        Show(result)
        
        ' Split the original string into the string after the delimiter and the 
        ' remainder of the original string after the delimiter.
        Console.WriteLine("1e) Split a string delimited by characters and " & _
                          "return 2 non-empty elements:")
        result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
        Show(result)
        
        ' ------------------------------------------------------------------------------
        ' Split a string delimited by another string.
        ' ------------------------------------------------------------------------------
        Console.WriteLine("2) Split a string delimited by another string:" & vbCrLf)
        
        ' Display the original string and delimiter string.
        Console.WriteLine("2a) The original string is ""{0}"".", s2)
        Console.WriteLine("The delimiter string is ""{0}""." & vbCrLf, stringSeparators(0))
        
        ' Split a string delimited by another string and return all elements.
        Console.WriteLine("2b) Split a string delimited by another string and " & _
                          "return all elements:")
        result = s2.Split(stringSeparators, StringSplitOptions.None)
        Show(result)
        
        ' Split the original string at the delimiter and return all non-empty elements.
        Console.WriteLine("2c) Split a string delimited by another string and " & _
                          "return all non-empty elements:")
        result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)
        Show(result)
        
        ' Split the original string into the empty string before the 
        ' delimiter and the remainder of the original string after the delimiter.
        Console.WriteLine("2d) Split a string delimited by another string and " & _
                          "return 2 elements:")
        result = s2.Split(stringSeparators, 2, StringSplitOptions.None)
        Show(result)
        
        ' Split the original string into the string after the delimiter and the 
        ' remainder of the original string after the delimiter.
        Console.WriteLine("2e) Split a string delimited by another string and " & _
                          "return 2 non-empty elements:")
        result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
        Show(result)
    
    End Sub
    
    
    ' Display the array of separated strings.
    Public Shared Sub Show(ByVal entries() As String) 
        Console.WriteLine("The return value contains these {0} elements:", entries.Length)
        Dim entry As String
        For Each entry In  entries
            Console.Write("<{0}>", entry)
        Next entry
        Console.Write(vbCrLf & vbCrLf)
    
    End Sub
End Class 'Sample
'
'This example produces the following results:
'
'1) Split a string delimited by characters:
'
'1a )The original string is ",ONE,,TWO,,,THREE,,".
'The delimiter character is ','.
'
'1b) Split a string delimited by characters and return all elements:
'The return value contains these 9 elements:
'<><ONE><><TWO><><><THREE><><>
'
'1c) Split a string delimited by characters and return all non-empty elements:
'The return value contains these 3 elements:
'<ONE><TWO><THREE>
'
'1d) Split a string delimited by characters and return 2 elements:
'The return value contains these 2 elements:
'<><ONE,,TWO,,,THREE,,>
'
'1e) Split a string delimited by characters and return 2 non-empty elements:
'The return value contains these 2 elements:
'<ONE><TWO,,,THREE,,>
'
'2) Split a string delimited by another string:
'
'2a) The original string is "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".
'The delimiter string is "[stop]".
'
'2b) Split a string delimited by another string and return all elements:
'The return value contains these 9 elements:
'<><ONE><><TWO><><><THREE><><>
'
'2c) Split a string delimited by another string and return all non-empty elements:
'The return value contains these 3 elements:
'<ONE><TWO><THREE>
'
'2d) Split a string delimited by another string and return 2 elements:
'The return value contains these 2 elements:
'<><ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]>
'
'2e) Split a string delimited by another string and return 2 non-empty elements:
'The return value contains these 2 elements:
'<ONE><TWO[stop][stop][stop]THREE[stop][stop]>
'

備註

分隔符號不會包含在傳回之陣列的元素中。Delimiter characters are not included in the elements of the returned array.

如果這個實例不包含中separator的任何字元, count或參數為1,則傳回的陣列會由包含這個實例的單一元素所組成。If this instance does not contain any of the characters in separator, or the count parameter is 1, the returned array consists of a single element that contains this instance. 如果參數是null或不包含任何字元,則會假設空白字元為分隔符號。 separatorIf the separator parameter is null or contains no characters, white-space characters are assumed to be the delimiters. 空白字元是由 Unicode 標準所定義,而且true會在傳遞Char.IsWhiteSpace給方法時傳回。White-space characters are defined by the Unicode standard and return true if they are passed to the Char.IsWhiteSpace method. 不過,如果separator呼叫這個方法多載的參數是,編譯器null多載解析就會失敗。However, if the separator parameter in the call to this method overload is null, compiler overload resolution fails. 若要明確識別被呼叫的方法,您的程式碼必須指出 null 的類型。To unambiguously identify the called method, your code must indicate the type of the null. 下列範例示範幾種明確識別此多載的方法。The following example shows several ways to unambiguously identify this overload.

string phrase = "The quick  brown fox";
string[] words;

words = phrase.Split(default(Char[]), 3, StringSplitOptions.RemoveEmptyEntries);

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

words = phrase.Split(null as char[], 3, StringSplitOptions.RemoveEmptyEntries);
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)

如果參數為零, options或參數為RemoveEmptyEntries ,且這個實例的長度為零,則會傳回空陣列。 countIf the count parameter is zero, or the options parameter is RemoveEmptyEntries and the length of this instance is zero, an empty array is returned.

separator每個元素都會定義個別的分隔符號。Each element of separator defines a separate delimiter character. 如果參數為None,且兩個分隔符號是連續的,或在這個實例的開頭或結尾找到分隔符號,則對應的陣列元素會Empty包含。 optionsIf the options parameter is None, and two delimiters are adjacent or a delimiter is found at the beginning or end of this instance, the corresponding array element contains Empty.

如果此實例中有count多個子字串,則會在count傳回值的第一個count減1個元素中傳回第一個減1子字串,而這個實例中的其餘字元會在最後一個傳回值的元素。If there are more than count substrings in this instance, the first count minus 1 substrings are returned in the first count minus 1 elements of the return value, and the remaining characters in this instance are returned in the last element of the return value.

如果count大於子字串的數目,則會傳回可用的子字串,而且不會擲回任何例外狀況。If count is greater than the number of substrings, the available substrings are returned and no exception is thrown.

效能考量Performance Considerations

方法會為傳回的陣列物件String和每個陣列元素的物件配置記憶體。 SplitThe Split methods allocate memory for the returned array object and a String object for each array element. 如果您的應用程式需要最佳效能,或是在您的應用程式中管理記憶體配置非常IndexOf重要IndexOfAny ,請考慮使用或Compare方法,並選擇性地選擇方法,以在字串中尋找子字串。If your application requires optimal performance or if managing memory allocation is critical in your application, consider using the IndexOf or IndexOfAny method, and optionally the Compare method, to locate a substring within a string.

如果您要在分隔字元處分割字串,請使用IndexOfIndexOfAny方法來尋找字串中的分隔符號。If you are splitting a string at a separator character, use the IndexOf or IndexOfAny method to locate a separator character in the string. 如果您要在分隔符號字串處分割字串,請使用IndexOfIndexOfAny方法來尋找分隔符號字串的第一個字元。If you are splitting a string at a separator string, use the IndexOf or IndexOfAny method to locate the first character of the separator string. 然後使用Compare方法來判斷第一個字元之後的字元是否等於分隔符號字串的其餘字元。Then use the Compare method to determine whether the characters after that first character are equal to the remaining characters of the separator string.

此外,如果使用同一組字元來分割多個Split方法呼叫中的字串,請考慮建立單一陣列,並在每個方法呼叫中參考它。In addition, if the same set of characters is used to split strings in multiple Split method calls, consider creating a single array and referencing it in each method call. 這會大幅降低每個方法呼叫的額外負荷。This significantly reduces the additional overhead of each method call.

給呼叫者的注意事項

Trim(Char[]) null separator在和舊版中, Split(Char[])如果傳遞的方法是或不包含任何字元,則方法會使用稍微不同的字元集來分割字串,而不是方法所做的.NET Framework 3.5.NET Framework 3.5修剪字串。In the .NET Framework 3.5.NET Framework 3.5 and earlier versions, if the Split(Char[]) method is passed a separator that is null or contains no characters, the method uses a slightly different set of characters to split the string than the Trim(Char[]) method does to trim the string. 從 .NET Framework 4 開始,這兩種方法都會使用一組相同的 Unicode 空白字元。Starting with the .NET Framework 4, both methods use an identical set of Unicode white-space characters.

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

傳回

String[]

Split(String[], Int32, StringSplitOptions) Split(String[], Int32, StringSplitOptions) Split(String[], Int32, StringSplitOptions) Split(String[], Int32, StringSplitOptions)

根據陣列中的字串分割字串成最大數目的子字串。Splits a string into a maximum number of substrings based on the strings in an array. 您可以指定子字串是否包含空的陣列元素。You can specify whether the substrings include empty array elements.

public:
 cli::array <System::String ^> ^ Split(cli::array <System::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[]
Public Function Split (separator As String(), count As Integer, options As StringSplitOptions) As String()

參數

separator
String[]

字串陣列 (可分隔這個字串中的子字串)、不含任何分隔符號的空陣列,或 nullA string array that delimits the substrings in this string, an empty array that contains no delimiters, or null.

count
Int32 Int32 Int32 Int32

要傳回的子字串之最大數目。The maximum number of substrings to return.

options
StringSplitOptions StringSplitOptions StringSplitOptions StringSplitOptions

RemoveEmptyEntries 表示要省略傳回陣列中的空陣列項目,否則 None 表示要包含傳回陣列中的空陣列項目。RemoveEmptyEntries to omit empty array elements from the array returned; or None to include empty array elements in the array returned.

傳回

String[]

陣列,其項目包含了這個字串中由 separator 內的一或多個字串所分隔的子字串。An array whose elements contain the substrings in this string that are delimited by one or more strings in separator. 如需詳細資訊,請參閱<備註>一節。For more information, see the Remarks section.

例外狀況

options 不是其中一個 StringSplitOptions 值。options is not one of the StringSplitOptions values.

範例

下列範例會使用StringSplitOptions列舉來包含或排除方法所Split產生的子字串。The following example uses the StringSplitOptions enumeration to include or exclude substrings generated by the Split method.

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

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

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

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

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

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

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

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

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

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

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

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

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

/*
This example produces the following results:

1) Split a string delimited by characters:

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

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

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

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

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

2) Split a string delimited by another string:

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

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

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

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

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

*/

' This example demonstrates the String() methods that use
' the StringSplitOptions enumeration.
Class Sample
    Public Shared Sub Main() 
        Dim s1 As String = ",ONE,,TWO,,,THREE,,"
        Dim s2 As String = "[stop]" & _
                           "ONE[stop][stop]" & _
                           "TWO[stop][stop][stop]" & _
                           "THREE[stop][stop]"
        Dim charSeparators() As Char = {","c}
        Dim stringSeparators() As String = {"[stop]"}
        Dim result() As String
        ' ------------------------------------------------------------------------------
        ' Split a string delimited by characters.
        ' ------------------------------------------------------------------------------
        Console.WriteLine("1) Split a string delimited by characters:" & vbCrLf)
        
        ' Display the original string and delimiter characters.
        Console.WriteLine("1a )The original string is ""{0}"".", s1)
        Console.WriteLine("The delimiter character is '{0}'." & vbCrLf, charSeparators(0))
        
        ' Split a string delimited by characters and return all elements.
        Console.WriteLine("1b) Split a string delimited by characters and " & _
                          "return all elements:")
        result = s1.Split(charSeparators, StringSplitOptions.None)
        Show(result)
        
        ' Split a string delimited by characters and return all non-empty elements.
        Console.WriteLine("1c) Split a string delimited by characters and " & _
                          "return all non-empty elements:")
        result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries)
        Show(result)
        
        ' Split the original string into the string and empty string before the 
        ' delimiter and the remainder of the original string after the delimiter.
        Console.WriteLine("1d) Split a string delimited by characters and " & _
                          "return 2 elements:")
        result = s1.Split(charSeparators, 2, StringSplitOptions.None)
        Show(result)
        
        ' Split the original string into the string after the delimiter and the 
        ' remainder of the original string after the delimiter.
        Console.WriteLine("1e) Split a string delimited by characters and " & _
                          "return 2 non-empty elements:")
        result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
        Show(result)
        
        ' ------------------------------------------------------------------------------
        ' Split a string delimited by another string.
        ' ------------------------------------------------------------------------------
        Console.WriteLine("2) Split a string delimited by another string:" & vbCrLf)
        
        ' Display the original string and delimiter string.
        Console.WriteLine("2a) The original string is ""{0}"".", s2)
        Console.WriteLine("The delimiter string is ""{0}""." & vbCrLf, stringSeparators(0))
        
        ' Split a string delimited by another string and return all elements.
        Console.WriteLine("2b) Split a string delimited by another string and " & _
                          "return all elements:")
        result = s2.Split(stringSeparators, StringSplitOptions.None)
        Show(result)
        
        ' Split the original string at the delimiter and return all non-empty elements.
        Console.WriteLine("2c) Split a string delimited by another string and " & _
                          "return all non-empty elements:")
        result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)
        Show(result)
        
        ' Split the original string into the empty string before the 
        ' delimiter and the remainder of the original string after the delimiter.
        Console.WriteLine("2d) Split a string delimited by another string and " & _
                          "return 2 elements:")
        result = s2.Split(stringSeparators, 2, StringSplitOptions.None)
        Show(result)
        
        ' Split the original string into the string after the delimiter and the 
        ' remainder of the original string after the delimiter.
        Console.WriteLine("2e) Split a string delimited by another string and " & _
                          "return 2 non-empty elements:")
        result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
        Show(result)
    
    End Sub
    
    
    ' Display the array of separated strings.
    Public Shared Sub Show(ByVal entries() As String) 
        Console.WriteLine("The return value contains these {0} elements:", entries.Length)
        Dim entry As String
        For Each entry In  entries
            Console.Write("<{0}>", entry)
        Next entry
        Console.Write(vbCrLf & vbCrLf)
    
    End Sub
End Class 'Sample
'
'This example produces the following results:
'
'1) Split a string delimited by characters:
'
'1a )The original string is ",ONE,,TWO,,,THREE,,".
'The delimiter character is ','.
'
'1b) Split a string delimited by characters and return all elements:
'The return value contains these 9 elements:
'<><ONE><><TWO><><><THREE><><>
'
'1c) Split a string delimited by characters and return all non-empty elements:
'The return value contains these 3 elements:
'<ONE><TWO><THREE>
'
'1d) Split a string delimited by characters and return 2 elements:
'The return value contains these 2 elements:
'<><ONE,,TWO,,,THREE,,>
'
'1e) Split a string delimited by characters and return 2 non-empty elements:
'The return value contains these 2 elements:
'<ONE><TWO,,,THREE,,>
'
'2) Split a string delimited by another string:
'
'2a) The original string is "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".
'The delimiter string is "[stop]".
'
'2b) Split a string delimited by another string and return all elements:
'The return value contains these 9 elements:
'<><ONE><><TWO><><><THREE><><>
'
'2c) Split a string delimited by another string and return all non-empty elements:
'The return value contains these 3 elements:
'<ONE><TWO><THREE>
'
'2d) Split a string delimited by another string and return 2 elements:
'The return value contains these 2 elements:
'<><ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]>
'
'2e) Split a string delimited by another string and return 2 non-empty elements:
'The return value contains these 2 elements:
'<ONE><TWO[stop][stop][stop]THREE[stop][stop]>
'

備註

傳回值詳細資料Return value details

分隔符號字串不會包含在傳回之陣列的元素中。Delimiter strings are not included in the elements of the returned array.

如果這個實例不包含中separator的任何字串, count或參數為1,則傳回的陣列會由包含這個實例的單一元素所組成。If this instance does not contain any of the strings in separator, or the count parameter is 1, the returned array consists of a single element that contains this instance. 如果參數是null或不包含任何字元,則會假設空白字元為分隔符號。 separatorIf the separator parameter is null or contains no characters, white-space characters are assumed to be the delimiters. 空白字元是由 Unicode 標準所定義,而且true會在傳遞Char.IsWhiteSpace給方法時傳回。White-space characters are defined by the Unicode standard and return true if they are passed to the Char.IsWhiteSpace method. 不過,如果separator呼叫這個方法多載的參數是,編譯器null多載解析就會失敗。However, if the separator parameter in the call to this method overload is null, compiler overload resolution fails. 若要明確識別被呼叫的方法,您的程式碼必須指出null的型別。To unambiguously identify the called method, your code must indicate the type of the null. 下列範例示範幾種明確識別此多載的方法。The following example shows several ways to unambiguously identify this overload.

string phrase = "The quick  brown fox";
string[] words;

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

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

words = phrase.Split(null as string[], 3, StringSplitOptions.RemoveEmptyEntries);
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)

如果參數為零, options或參數為RemoveEmptyEntries ,且這個實例的長度為零,則會傳回空陣列。 countIf the count parameter is zero, or the options parameter is RemoveEmptyEntries and the length of this instance is zero, an empty array is returned.

separator每個專案都會定義個別的分隔符號,其中包含一或多個字元。Each element of separator defines a separate delimiter that consists of one or more characters. 如果參數為None,且兩個分隔符號是連續的,或在這個實例的開頭或結尾找到分隔符號,則對應的陣列元素會Empty包含。 optionsIf the options parameter is None, and two delimiters are adjacent or a delimiter is found at the beginning or end of this instance, the corresponding array element contains Empty.

如果此實例中有count多個子字串,則會在count傳回值的第一個count減1個元素中傳回第一個減1子字串,而這個實例中的其餘字元會在最後一個傳回值的元素。If there are more than count substrings in this instance, the first count minus 1 substrings are returned in the first count minus 1 elements of the return value, and the remaining characters in this instance are returned in the last element of the return value.

如果count大於子字串的數目,則會傳回可用的子字串,而且不會擲回任何例外狀況。If count is greater than the number of substrings, the available substrings are returned and no exception is thrown.

分隔符號陣列The separator array

如果中separator的任何元素包含多個字元,則會將整個子字串視為分隔符號。If any of the elements in separator consists of multiple characters, the entire substring is considered a delimiter. 例如,如果中separator的其中一個元素為 "10",則嘗試分割字串 "This10is10a10string"。For example, if one of the elements in separator is "10", attempting to split the string "This10is10a10string." 傳回這四個元素的陣列: {"This","is","a","string"。returns this four-element array: { "This", "is", "a", "string." }.}.

比較詳細資料Comparison details

方法會將這個字串中的子字串,以separator參數中的一或多個字串分隔,並傳回這些子字串做為陣列的元素。 SplitThe Split method extracts the substrings in this string that are delimited by one or more of the strings in the separator parameter, and returns those substrings as elements of an array.

Split方法會使用區分大小寫的序數排序規則來執行比較,藉以尋找分隔符號。The Split method looks for delimiters by performing comparisons using case-sensitive ordinal sort rules. 如需有關 word、string 和序數排序的詳細資訊,請System.Globalization.CompareOptions參閱列舉。For more information about word, string, and ordinal sorts, see the System.Globalization.CompareOptions enumeration.

方法會忽略其值為separator null或空字串("")的任何元素。 SplitThe Split method ignores any element of separator whose value is null or the empty string ("").

若要避免在中separator的字串具有一般字元時的不明確結果,此Split方法會從實例值的開頭繼續進行,並比對中的第一個separator專案,該專案等於中的分隔符號。示例.To avoid ambiguous results when strings in separator have characters in common, the Split method proceeds from the beginning to the end of the value of the instance, and matches the first element in separator that is equal to a delimiter in the instance. 在實例中遇到子字串的順序,會優先于中separator的專案順序。The order in which substrings are encountered in the instance takes precedence over the order of elements in separator.

例如,假設其值為 "abcdef" 的實例。For example, consider an instance whose value is "abcdef". 如果中separator的第一個元素是 "ef",而第二個元素是 "bcde",則分割作業的結果會是 "a" 和 "f"。If the first element in separator was "ef" and the second element was "bcde", the result of the split operation would be "a" and "f". 這是因為遇到 "bcde" 實例中的子字串,且在遇到子字串 "f separator " 之前,符合中的元素。This is because the substring in the instance, "bcde", is encountered and matches an element in separator before the substring "f" is encountered.

不過,如果的第一個元素separator是 "bcd",而第二個元素是 "bc",則分割作業的結果會是 "a" 和 "ef"。However, if the first element of separator was "bcd" and the second element was "bc", the result of the split operation would be "a" and "ef". 這是因為「bcd」是中separator的第一個分隔符號,符合實例中的分隔符號。This is because "bcd" is the first delimiter in separator that matches a delimiter in the instance. 如果分隔符號的順序已反轉,因此第一個元素是 "bc",而第二個元素是 "bcd",則結果會是 "a" 和 "def"。If the order of the separators was reversed so the first element was "bc" and the second element was "bcd", the result would be "a" and "def".

效能考量Performance considerations

方法會為傳回的陣列物件String和每個陣列元素的物件配置記憶體。 SplitThe Split methods allocate memory for the returned array object and a String object for each array element. 如果您的應用程式需要最佳效能,或是在您的應用程式中管理記憶體配置非常IndexOf重要IndexOfAny ,請考慮使用或Compare方法,並選擇性地選擇方法,以在字串中尋找子字串。If your application requires optimal performance or if managing memory allocation is critical in your application, consider using the IndexOf or IndexOfAny method, and optionally the Compare method, to locate a substring within a string.

如果您要在分隔字元處分割字串,請使用IndexOfIndexOfAny方法來尋找字串中的分隔符號。If you are splitting a string at a separator character, use the IndexOf or IndexOfAny method to locate a separator character in the string. 如果您要在分隔符號字串處分割字串,請使用IndexOfIndexOfAny方法來尋找分隔符號字串的第一個字元。If you are splitting a string at a separator string, use the IndexOf or IndexOfAny method to locate the first character of the separator string. 然後使用Compare方法來判斷第一個字元之後的字元是否等於分隔符號字串的其餘字元。Then use the Compare method to determine whether the characters after that first character are equal to the remaining characters of the separator string.

此外,如果使用同一組字元來分割多個Split方法呼叫中的字串,請考慮建立單一陣列,並在每個方法呼叫中參考它。In addition, if the same set of characters is used to split strings in multiple Split method calls, consider creating a single array and referencing it in each method call. 這會大幅降低每個方法呼叫的額外負荷。This significantly reduces the additional overhead of each method call.

給呼叫者的注意事項

Trim(Char[]) null separator在和舊版中, Split(Char[])如果傳遞的方法是或不包含任何字元,則方法會使用稍微不同的字元集來分割字串,而不是方法所做的.NET Framework 3.5.NET Framework 3.5修剪字串。In the .NET Framework 3.5.NET Framework 3.5 and earlier versions, if the Split(Char[]) method is passed a separator that is null or contains no characters, the method uses a slightly different set of characters to split the string than the Trim(Char[]) method does to trim the string. 從 .NET Framework 4 開始,這兩種方法都會使用一組相同的 Unicode 空白字元。Starting with the .NET Framework 4, both methods use an identical set of Unicode white-space characters.

Split(String[], StringSplitOptions) Split(String[], StringSplitOptions) Split(String[], StringSplitOptions) Split(String[], StringSplitOptions)

根據陣列中的字串分割字串成子字串。Splits a string into substrings based on the strings in an array. 您可以指定子字串是否包含空的陣列元素。You can specify whether the substrings include empty array elements.

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

參數

separator
String[]

字串陣列 (可分隔這個字串中的子字串)、不含任何分隔符號的空陣列,或 nullA string array that delimits the substrings in this string, an empty array that contains no delimiters, or null.

options
StringSplitOptions StringSplitOptions StringSplitOptions StringSplitOptions

RemoveEmptyEntries 表示要省略傳回陣列中的空陣列項目,否則 None 表示要包含傳回陣列中的空陣列項目。RemoveEmptyEntries to omit empty array elements from the array returned; or None to include empty array elements in the array returned.

傳回

String[]

陣列,其項目包含了這個字串中由 separator 內的一或多個字串所分隔的子字串。An array whose elements contain the substrings in this string that are delimited by one or more strings in separator. 如需詳細資訊,請參閱<備註>一節。For more information, see the Remarks section.

例外狀況

options 不是其中一個 StringSplitOptions 值。options is not one of the StringSplitOptions values.

範例

下列範例說明藉由String.Split(String[], StringSplitOptions)呼叫字串的方法,並將其options參數與StringSplitOptions.None和相等, StringSplitOptions.RemoveEmptyEntries來傳回陣列中的差異。The following example illustrates the difference in the arrays returned by calling a string's String.Split(String[], StringSplitOptions) method with its options parameter equal to StringSplitOptions.None and 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   \"{0}\".", source);
Console.WriteLine();
Console.WriteLine("Using the delimiter string:\n   \"{0}\"", 
                  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("   ");
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 ({0} elements):", 
                  result.Length);
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'
Module Example
   Public Sub Main()
      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()
   End Sub
End Module
' 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'

下列範例會定義包含標點符號和空白字元的分隔符號陣列。The following example defines an array of separators that include punctuation and white-space characters. 將這個陣列連同的值StringSplitOptions.RemoveEmptyEntries傳遞Split(String[], StringSplitOptions)給方法,會傳回由字串中的個別單字所組成的陣列。Passing this array along with a value of StringSplitOptions.RemoveEmptyEntries to the Split(String[], StringSplitOptions) method returns an array that consists of the individual words from the string.

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
Module Example
   Public Sub Main()
      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
End Module
' The example displays the following output:
'       The
'       handsome
'       energetic
'       young
'       dog
'       was
'       playing
'       with
'       his
'       smaller
'       more
'       lethargic
'       litter
'       mate

請注意,會呼叫方法,並options將引數StringSplitOptions.RemoveEmptyEntries設為。Note that the method is called with the options argument set to StringSplitOptions.RemoveEmptyEntries. 這可防止傳回的陣列在String.Empty標點符號與空白字元之間包含代表空白子字串的值。This prevents the returned array from including String.Empty values that represent empty substring matches between punctuation marks and white-space characters.

備註

當字串以一組已知的字串分隔時,您可以使用Split方法,將它分隔成子字串。When a string is delimited by a known set of strings, you can use the Split method to separate it into substrings.

傳回值詳細資料Return value details

分隔符號字串不會包含在傳回之陣列的元素中。Delimiter strings are not included in the elements of the returned array. 例如,如果separator陣列包含字串 "--",而目前字串實例的值是 "aa--bb-cc",則方法會傳回包含三個元素的陣列: "aa"、"bb" 和 "cc"。For example, if the separator array includes the string "--" and the value of the current string instance is "aa--bb-cc", the method returns an array that contains three elements: "aa", "bb", and "cc".

如果這個實例不包含中separator的任何字串,則傳回的陣列會由包含這個實例的單一元素所組成。If this instance does not contain any of the strings in separator, the returned array consists of a single element that contains this instance.

如果參數為RemoveEmptyEntries ,且這個實例的長度為零,則方法會傳回空陣列。 optionsIf the options parameter is RemoveEmptyEntries and the length of this instance is zero, the method returns an empty array.

separator每個專案都會定義個別的分隔符號,其中包含一或多個字元。Each element of separator defines a separate delimiter that consists of one or more characters. 如果引數為None,且兩個分隔符號是連續的,或在這個實例的開頭或結尾找到分隔符號,則對應的陣列元素會包含String.EmptyoptionsIf the options argument is None, and two delimiters are adjacent or a delimiter is found at the beginning or end of this instance, the corresponding array element contains String.Empty. separator例如,如果包含兩個元素: "-" 和 "_",字串實例的值為 "- options _aa-_",而引數的值為,則方法None會傳回具有的字串陣列下列五個元素:For example, if separator includes two elements, "-" and "_", the value of the string instance is "-_aa-_", and the value of the options argument is None, the method returns a sting array with the following five elements:

  1. String.Empty,代表位於索引0的 "-" 子字串前面的空字串。String.Empty, which represents the empty string that precedes the "-" substring at index 0.

  2. String.Empty,代表位於索引0的 "-" 子字串與位於索引1的 "" 子字串之間的空字串。String.Empty, which represents the empty string between the "-" substring at index 0 and the "" substring at index 1.

  3. "aa","aa",

  4. String.Empty,代表位於索引4之 "" 子字串後面的空字串。String.Empty, which represents the empty string that follows the "" substring at index 4.

  5. String.Empty,代表緊接在索引5之 "-" 子字串後面的空字串。String.Empty, which represents the empty string that follows the "-" substring at index 5.

分隔符號陣列The separator array

如果中separator的任何元素包含多個字元,則會將整個子字串視為分隔符號。If any of the elements in separator consists of multiple characters, the entire substring is considered a delimiter. 例如,如果中separator的其中一個元素為 "10",則嘗試分割字串 "This10is10a10string"。For example, if one of the elements in separator is "10", attempting to split the string "This10is10a10string." 傳回下列四個元素的陣列: {"This","is","a","string"。returns the following four-element array: { "This", "is", "a", "string." }.}.

如果參數是null或不包含任何字元,則會假設空白字元為分隔符號。 separatorIf the separator parameter is null or contains no characters, white-space characters are assumed to be the delimiters. 空白字元是由 Unicode 標準所定義,而且true會在傳遞Char.IsWhiteSpace給方法時傳回。White-space characters are defined by the Unicode standard and return true if they are passed to the Char.IsWhiteSpace method.

如果呼叫這個方法多載的null參數是,編譯器多載解析就會失敗。separatorIf the separator parameter in the call to this method overload is null, compiler overload resolution fails. 若要明確識別被呼叫的方法,您的程式碼必須指出null的型別。To unambiguously identify the called method, your code must indicate the type of the null. 下列範例示範幾種明確識別此多載的方法。The following example shows several ways to unambiguously identify this overload.

string phrase = "The quick  brown fox";
string[] words;

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

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

words = phrase.Split(null as string[], StringSplitOptions.RemoveEmptyEntries);
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)

比較詳細資料Comparison details

方法會將這個字串中的子字串,以separator參數中的一或多個字串分隔,並傳回這些子字串做為陣列的元素。 SplitThe Split method extracts the substrings in this string that are delimited by one or more of the strings in the separator parameter, and returns those substrings as elements of an array.

Split方法會使用區分大小寫的序數排序規則來執行比較,藉以尋找分隔符號。The Split method looks for delimiters by performing comparisons using case-sensitive ordinal sort rules. 如需有關 word、string 和序數排序的詳細資訊,請System.Globalization.CompareOptions參閱列舉。For more information about word, string, and ordinal sorts, see the System.Globalization.CompareOptions enumeration.

方法會忽略其值為separator null或空字串("")的任何元素。 SplitThe Split method ignores any element of separator whose value is null or the empty string ("").

若要避免在中separator的字串具有一般字元時出現不明確的結果,此Split作業會從實例值的開頭開始進行,並separator符合中的第一個專案,該專案等於中的分隔符號。示例.To avoid ambiguous results when strings in separator have characters in common, the Split operation proceeds from the beginning to the end of the value of the instance, and matches the first element in separator that is equal to a delimiter in the instance. 在實例中遇到子字串的順序,會優先于中separator的專案順序。The order in which substrings are encountered in the instance takes precedence over the order of elements in separator.

例如,假設其值為 "abcdef" 的實例。For example, consider an instance whose value is "abcdef". 如果中separator的第一個元素是 "ef",而第二個元素是 "bcde",則分割作業的結果會是包含兩個元素 "a" 和 "f" 的字串陣列。If the first element in separator was "ef" and the second element was "bcde", the result of the split operation would be a string array that contains two elements, "a" and "f". 這是因為遇到 "bcde" 實例中的子字串,且在遇到子字串 "f separator " 之前,符合中的元素。This is because the substring in the instance, "bcde", is encountered and matches an element in separator before the substring "f" is encountered.

不過,如果的第一個元素separator是 "bcd",而第二個元素是 "bc",則分割作業的結果會是包含兩個元素 "a" 和 "ef" 的字串陣列。However, if the first element of separator was "bcd" and the second element was "bc", the result of the split operation would be a string array that contains two elements, "a" and "ef". 這是因為「bcd」是中separator的第一個分隔符號,符合實例中的分隔符號。This is because "bcd" is the first delimiter in separator that matches a delimiter in the instance. 如果分隔符號的順序已反轉,因此第一個元素是 "bc",而第二個元素是 "bcd",則結果會是包含兩個元素 "a" 和 "def" 的字串陣列。If the order of the separators was reversed so the first element was "bc" and the second element was "bcd", the result would be a string array that contains two elements, "a" and "def".

效能考量Performance considerations

方法會為傳回的陣列物件String和每個陣列元素的物件配置記憶體。 SplitThe Split methods allocate memory for the returned array object and a String object for each array element. 如果您的應用程式需要最佳效能,或是在您的應用程式中管理記憶體配置非常IndexOf重要IndexOfAny ,請考慮使用或Compare方法,並選擇性地選擇方法,以在字串中尋找子字串。If your application requires optimal performance or if managing memory allocation is critical in your application, consider using the IndexOf or IndexOfAny method, and optionally the Compare method, to locate a substring within a string.

如果您要在分隔字元處分割字串,請使用IndexOfIndexOfAny方法來尋找字串中的分隔符號。If you are splitting a string at a separator character, use the IndexOf or IndexOfAny method to locate a separator character in the string. 如果您要在分隔符號字串處分割字串,請使用IndexOfIndexOfAny方法來尋找分隔符號字串的第一個字元。If you are splitting a string at a separator string, use the IndexOf or IndexOfAny method to locate the first character of the separator string. 然後使用Compare方法來判斷第一個字元之後的字元是否等於分隔符號字串的其餘字元。Then use the Compare method to determine whether the characters after that first character are equal to the remaining characters of the separator string.

此外,如果使用同一組字元來分割多個Split方法呼叫中的字串,請考慮建立單一陣列,並在每個方法呼叫中參考它。In addition, if the same set of characters is used to split strings in multiple Split method calls, consider creating a single array and referencing it in each method call. 這會大幅降低每個方法呼叫的額外負荷。This significantly reduces the additional overhead of each method call.

給呼叫者的注意事項

Trim(Char[]) null separator在和舊版中, Split(Char[])如果傳遞的方法是或不包含任何字元,則方法會使用稍微不同的字元集來分割字串,而不是方法所做的.NET Framework 3.5.NET Framework 3.5修剪字串。In the .NET Framework 3.5.NET Framework 3.5 and earlier versions, if the Split(Char[]) method is passed a separator that is null or contains no characters, the method uses a slightly different set of characters to split the string than the Trim(Char[]) method does to trim the string. 從 .NET Framework 4 開始,這兩種方法都會使用一組相同的 Unicode 空白字元。Starting with the .NET Framework 4, both methods use an identical set of Unicode white-space characters.

Split(String, Int32, StringSplitOptions) Split(String, Int32, StringSplitOptions) Split(String, Int32, StringSplitOptions)

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

參數

傳回

String[]

Split(Char[], StringSplitOptions) Split(Char[], StringSplitOptions) Split(Char[], StringSplitOptions) Split(Char[], StringSplitOptions)

根據陣列中的字元分割字串成子字串。Splits a string into substrings based on the characters in an array. 您可以指定子字串是否包含空的陣列元素。You can specify whether the substrings include empty array elements.

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

參數

separator
Char[]

字串陣列 (可分隔這個字串中的子字串)、不含任何分隔符號的空陣列,或 nullA character array that delimits the substrings in this string, an empty array that contains no delimiters, or null.

options
StringSplitOptions StringSplitOptions StringSplitOptions StringSplitOptions

RemoveEmptyEntries 表示要省略傳回陣列中的空陣列項目,否則 None 表示要包含傳回陣列中的空陣列項目。RemoveEmptyEntries to omit empty array elements from the array returned; or None to include empty array elements in the array returned.

傳回

String[]

陣列,其項目包含了這個字串中由 separator 內的一或多個字元所分隔的子字串。An array whose elements contain the substrings in this string that are delimited by one or more characters in separator. 如需詳細資訊,請參閱<備註>一節。For more information, see the Remarks section.

例外狀況

options 不是其中一個 StringSplitOptions 值。options is not one of the StringSplitOptions values.

範例

下列範例會使用StringSplitOptions列舉來包含或排除方法所Split產生的子字串。The following example uses the StringSplitOptions enumeration to include or exclude substrings generated by the Split method.

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

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

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

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

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

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

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

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

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

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

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

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

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

/*
This example produces the following results:

1) Split a string delimited by characters:

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

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

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

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

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

2) Split a string delimited by another string:

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

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

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

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

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

*/

' This example demonstrates the String() methods that use
' the StringSplitOptions enumeration.
Class Sample
    Public Shared Sub Main() 
        Dim s1 As String = ",ONE,,TWO,,,THREE,,"
        Dim s2 As String = "[stop]" & _
                           "ONE[stop][stop]" & _
                           "TWO[stop][stop][stop]" & _
                           "THREE[stop][stop]"
        Dim charSeparators() As Char = {","c}
        Dim stringSeparators() As String = {"[stop]"}
        Dim result() As String
        ' ------------------------------------------------------------------------------
        ' Split a string delimited by characters.
        ' ------------------------------------------------------------------------------
        Console.WriteLine("1) Split a string delimited by characters:" & vbCrLf)
        
        ' Display the original string and delimiter characters.
        Console.WriteLine("1a )The original string is ""{0}"".", s1)
        Console.WriteLine("The delimiter character is '{0}'." & vbCrLf, charSeparators(0))
        
        ' Split a string delimited by characters and return all elements.
        Console.WriteLine("1b) Split a string delimited by characters and " & _
                          "return all elements:")
        result = s1.Split(charSeparators, StringSplitOptions.None)
        Show(result)
        
        ' Split a string delimited by characters and return all non-empty elements.
        Console.WriteLine("1c) Split a string delimited by characters and " & _
                          "return all non-empty elements:")
        result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries)
        Show(result)
        
        ' Split the original string into the string and empty string before the 
        ' delimiter and the remainder of the original string after the delimiter.
        Console.WriteLine("1d) Split a string delimited by characters and " & _
                          "return 2 elements:")
        result = s1.Split(charSeparators, 2, StringSplitOptions.None)
        Show(result)
        
        ' Split the original string into the string after the delimiter and the 
        ' remainder of the original string after the delimiter.
        Console.WriteLine("1e) Split a string delimited by characters and " & _
                          "return 2 non-empty elements:")
        result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
        Show(result)
        
        ' ------------------------------------------------------------------------------
        ' Split a string delimited by another string.
        ' ------------------------------------------------------------------------------
        Console.WriteLine("2) Split a string delimited by another string:" & vbCrLf)
        
        ' Display the original string and delimiter string.
        Console.WriteLine("2a) The original string is ""{0}"".", s2)
        Console.WriteLine("The delimiter string is ""{0}""." & vbCrLf, stringSeparators(0))
        
        ' Split a string delimited by another string and return all elements.
        Console.WriteLine("2b) Split a string delimited by another string and " & _
                          "return all elements:")
        result = s2.Split(stringSeparators, StringSplitOptions.None)
        Show(result)
        
        ' Split the original string at the delimiter and return all non-empty elements.
        Console.WriteLine("2c) Split a string delimited by another string and " & _
                          "return all non-empty elements:")
        result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)
        Show(result)
        
        ' Split the original string into the empty string before the 
        ' delimiter and the remainder of the original string after the delimiter.
        Console.WriteLine("2d) Split a string delimited by another string and " & _
                          "return 2 elements:")
        result = s2.Split(stringSeparators, 2, StringSplitOptions.None)
        Show(result)
        
        ' Split the original string into the string after the delimiter and the 
        ' remainder of the original string after the delimiter.
        Console.WriteLine("2e) Split a string delimited by another string and " & _
                          "return 2 non-empty elements:")
        result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
        Show(result)
    
    End Sub
    
    
    ' Display the array of separated strings.
    Public Shared Sub Show(ByVal entries() As String) 
        Console.WriteLine("The return value contains these {0} elements:", entries.Length)
        Dim entry As String
        For Each entry In  entries
            Console.Write("<{0}>", entry)
        Next entry
        Console.Write(vbCrLf & vbCrLf)
    
    End Sub
End Class 'Sample
'
'This example produces the following results:
'
'1) Split a string delimited by characters:
'
'1a )The original string is ",ONE,,TWO,,,THREE,,".
'The delimiter character is ','.
'
'1b) Split a string delimited by characters and return all elements:
'The return value contains these 9 elements:
'<><ONE><><TWO><><><THREE><><>
'
'1c) Split a string delimited by characters and return all non-empty elements:
'The return value contains these 3 elements:
'<ONE><TWO><THREE>
'
'1d) Split a string delimited by characters and return 2 elements:
'The return value contains these 2 elements:
'<><ONE,,TWO,,,THREE,,>
'
'1e) Split a string delimited by characters and return 2 non-empty elements:
'The return value contains these 2 elements:
'<ONE><TWO,,,THREE,,>
'
'2) Split a string delimited by another string:
'
'2a) The original string is "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".
'The delimiter string is "[stop]".
'
'2b) Split a string delimited by another string and return all elements:
'The return value contains these 9 elements:
'<><ONE><><TWO><><><THREE><><>
'
'2c) Split a string delimited by another string and return all non-empty elements:
'The return value contains these 3 elements:
'<ONE><TWO><THREE>
'
'2d) Split a string delimited by another string and return 2 elements:
'The return value contains these 2 elements:
'<><ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]>
'
'2e) Split a string delimited by another string and return 2 non-empty elements:
'The return value contains these 2 elements:
'<ONE><TWO[stop][stop][stop]THREE[stop][stop]>
'

備註

傳回值詳細資料Return value details

分隔符號( separator陣列中的字元)不會包含在傳回之陣列的元素中。Delimiter characters (the characters in the separator array) are not included in the elements of the returned array. 例如,如果separator陣列包含字元 "-",而目前字串實例的值是 "aa-bb-cc",則方法會傳回包含三個元素的陣列: "aa"、"bb" 和 "cc"。For example, if the separator array includes the character "-" and the value of the current string instance is "aa-bb-cc", the method returns an array that contains three elements: "aa", "bb", and "cc".

如果這個實例不包含中separator的任何字元,則傳回的陣列會由包含這個實例的單一元素所組成。If this instance does not contain any of the characters in separator, the returned array consists of a single element that contains this instance.

如果參數為RemoveEmptyEntries ,且這個實例的長度為零,則方法會傳回空陣列。 optionsIf the options parameter is RemoveEmptyEntries and the length of this instance is zero, the method returns an empty array.

separator每個元素都會定義個別的分隔符號,其中包含單一字元。Each element of separator defines a separate delimiter that consists of a single character. 如果引數為None,且兩個分隔符號是連續的,或在這個實例的開頭或結尾找到分隔符號,則對應的陣列元素會包含String.EmptyoptionsIf the options argument is None, and two delimiters are adjacent or a delimiter is found at the beginning or end of this instance, the corresponding array element contains String.Empty. separator例如,如果包含兩個元素: "-" 和 "_",字串實例的值為 "- options _aa-_",而引數的值為,則方法None會傳回字串陣列,其中包含下列五個元素:For example, if separator includes two elements, "-" and "_", the value of the string instance is "-_aa-_", and the value of the options argument is None, the method returns a string array with the following five elements:

  1. String.Empty,代表位於索引0的 "-" 字元之前的空字串。String.Empty, which represents the empty string that precedes the "-" character at index 0.

  2. String.Empty,代表位於索引0的 "-" 字元與位於索引1的 "" 字元之間的空字串。String.Empty, which represents the empty string between the "-" character at index 0 and the "" character at index 1.

  3. "aa","aa",

  4. String.Empty,代表緊接在索引4之 "" 字元後面的空字串。String.Empty, which represents the empty string that follows the "" character at index 4.

  5. String.Empty,代表緊接在索引5之 "-" 字元後面的空字串。String.Empty, which represents the empty string that follows the "-" character at index 5.

分隔符號陣列The separator array

如果參數是null或不包含任何字元,則會假設空白字元為分隔符號。 separatorIf the separator parameter is null or contains no characters, white-space characters are assumed to be the delimiters. 空白字元是由 Unicode 標準所定義,而且true會在傳遞Char.IsWhiteSpace給方法時傳回。White-space characters are defined by the Unicode standard and return true if they are passed to the Char.IsWhiteSpace method.

如果呼叫這個方法多載的null參數是,編譯器多載解析就會失敗。separatorIf the separator parameter in the call to this method overload is null, compiler overload resolution fails. 若要明確識別被呼叫的方法,您的程式碼必須指出null的型別。To unambiguously identify the called method, your code must indicate the type of the null. 下列範例示範幾種明確識別此多載的方法。The following example shows several ways to unambiguously identify this overload.

string phrase = "The quick  brown fox";
string[] words;

words = phrase.Split(default(Char[]), StringSplitOptions.RemoveEmptyEntries);

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

words = phrase.Split(null as char[], StringSplitOptions.RemoveEmptyEntries);
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)

比較詳細資料Comparison details

方法會將此字串中的子字串,以separator參數中的一或多個字元分隔,並傳回這些子字串做為陣列的元素。 SplitThe Split method extracts the substrings in this string that are delimited by one or more of the characters in the separator parameter, and returns those substrings as elements of an array.

Split方法會使用區分大小寫的序數排序規則來執行比較,藉以尋找分隔符號。The Split method looks for delimiters by performing comparisons using case-sensitive ordinal sort rules. 如需有關 word、string 和序數排序的詳細資訊,請System.Globalization.CompareOptions參閱列舉。For more information about word, string, and ordinal sorts, see the System.Globalization.CompareOptions enumeration.

效能考量Performance Considerations

方法會為傳回的陣列物件String和每個陣列元素的物件配置記憶體。 SplitThe Split methods allocate memory for the returned array object and a String object for each array element. 如果您的應用程式需要最佳效能,或是在您的應用程式中管理記憶體配置非常IndexOf重要IndexOfAny ,請考慮使用或Compare方法,並選擇性地選擇方法,以在字串中尋找子字串。If your application requires optimal performance or if managing memory allocation is critical in your application, consider using the IndexOf or IndexOfAny method, and optionally the Compare method, to locate a substring within a string.

如果您要在分隔字元處分割字串,請使用IndexOfIndexOfAny方法來尋找字串中的分隔符號。If you are splitting a string at a separator character, use the IndexOf or IndexOfAny method to locate a separator character in the string. 如果您要在分隔符號字串處分割字串,請使用IndexOfIndexOfAny方法來尋找分隔符號字串的第一個字元。If you are splitting a string at a separator string, use the IndexOf or IndexOfAny method to locate the first character of the separator string. 然後使用Compare方法來判斷第一個字元之後的字元是否等於分隔符號字串的其餘字元。Then use the Compare method to determine whether the characters after that first character are equal to the remaining characters of the separator string.

此外,如果使用同一組字元來分割多個Split方法呼叫中的字串,請考慮建立單一陣列,並在每個方法呼叫中參考它。In addition, if the same set of characters is used to split strings in multiple Split method calls, consider creating a single array and referencing it in each method call. 這會大幅降低每個方法呼叫的額外負荷。This significantly reduces the additional overhead of each method call.

給呼叫者的注意事項

Trim(Char[]) null separator在和舊版中, Split(Char[])如果傳遞的方法是或不包含任何字元,則方法會使用稍微不同的字元集來分割字串,而不是方法所做的.NET Framework 3.5.NET Framework 3.5修剪字串。In the .NET Framework 3.5.NET Framework 3.5 and earlier versions, if the Split(Char[]) method is passed a separator that is null or contains no characters, the method uses a slightly different set of characters to split the string than the Trim(Char[]) method does to trim the string. 從 .NET Framework 4 開始,這兩種方法都會使用一組相同的 Unicode 空白字元。Starting with the .NET Framework 4, both methods use an identical set of Unicode white-space characters.

Split(Char[], Int32) Split(Char[], Int32) Split(Char[], Int32) Split(Char[], Int32)

根據陣列中的字元分割字串成最大數目的子字串。Splits a string into a maximum number of substrings based on the characters in an array. 您也要指定傳回的子字串之最大數目。You also specify the maximum number of substrings to return.

public:
 cli::array <System::String ^> ^ Split(cli::array <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[]

字串陣列 (可分隔這個字串中的子字串)、不含任何分隔符號的空陣列,或 nullA character array that delimits the substrings in this string, an empty array that contains no delimiters, or null.

count
Int32 Int32 Int32 Int32

要傳回的子字串之最大數目。The maximum number of substrings to return.

傳回

String[]

陣列,其項目中包含了這個執行個體中的子字串,由 separator 內的一或多個字元分隔。An array whose elements contain the substrings in this instance that are delimited by one or more characters in separator. 如需詳細資訊,請參閱<備註>一節。For more information, see the Remarks section.

例外狀況

範例

下列範例示範如何count影響所Split傳回的字串數目。The following example demonstrates how count affects the number of strings returned by Split.

string delimStr = " ,.:";
char [] delimiter = delimStr.ToCharArray();
string words = "one two,three:four.";
string [] split = null;

Console.WriteLine("The delimiters are -{0}-", delimStr);
for (int x = 1; x <= 5; x++) 
{
   split = words.Split(delimiter, x);
   Console.WriteLine("\ncount = {0,2} ..............", x);
   foreach (var s in split) 
   {
       Console.WriteLine("-{0}-", s);
   }
}

// The example displays the following output:
//       The delimiters are - ,.:-
//       count =  1 ..............
//       -one two,three:four.-
//       count =  2 ..............
//       -one-
//       -two,three:four.-
//       count =  3 ..............
//       -one-
//       -two-
//       -three:four.-
//       count =  4 ..............
//       -one-
//       -two-
//       -three-
//       -four.-
//       count =  5 ..............
//       -one-
//       -two-
//       -three-
//       -four-
//       --
Public Class StringSplit2
   Public Shared Sub Main()
      
      Dim delimStr As String = " ,.:"
      Dim delimiter As Char() = delimStr.ToCharArray()
      Dim words As String = "one two,three:four."
      Dim split As String() = Nothing
      
      Console.WriteLine("The delimiters are -{0}-", delimStr)
      Dim x As Integer
      For x = 1 To 5
         split = words.Split(delimiter, x)
         Console.WriteLine(ControlChars.Cr + "count = {0,2} ..............", x)
         Dim s As String
         For Each s In  split
            Console.WriteLine("-{0}-", s)
         Next s
      Next x
   End Sub 
End Class 
' The example displays the following output:
'       The delimiters are - ,.:-
'       count =  1 ..............
'       -one two,three:four.-
'       count =  2 ..............
'       -one-
'       -two,three:four.-
'       count =  3 ..............
'       -one-
'       -two-
'       -three:four.-
'       count =  4 ..............
'       -one-
'       -two-
'       -three-
'       -four.-
'       count =  5 ..............
'       -one-
'       -two-
'       -three-
'       -four-
'       --

備註

分隔符號不會包含在傳回之陣列的元素中。Delimiter characters are not included in the elements of the returned array.

如果這個實例不包含中separator的任何字元,則傳回的陣列會由包含這個實例的單一元素所組成。If this instance does not contain any of the characters in separator, the returned array consists of a single element that contains this instance. 如果count為零,則會傳回空陣列。If count is zero, an empty array is returned.

如果參數是null或不包含任何字元,則會假設空白字元為分隔符號。 separatorIf the separator parameter is null or contains no characters, white-space characters are assumed to be the delimiters. 空白字元是由 Unicode 標準所定義,而且true會在傳遞Char.IsWhiteSpace給方法時傳回。White-space characters are defined by the Unicode standard and return true if they are passed to the Char.IsWhiteSpace method.

separator每個元素都會定義個別的分隔符號。Each element of separator defines a separate delimiter character. 如果兩個分隔符號相鄰,或在這個實例的開頭或結尾找到分隔符號,則對應的陣列元素會包含EmptyIf two delimiters are adjacent, or a delimiter is found at the beginning or end of this instance, the corresponding array element contains Empty.

如果此實例中有count多個子字串,則會在count傳回值的第一個count減1個元素中傳回第一個減1子字串,而這個實例中的其餘字元會在最後一個傳回值的元素。If there are more than count substrings in this instance, the first count minus 1 substrings are returned in the first count minus 1 elements of the return value, and the remaining characters in this instance are returned in the last element of the return value.

如果count大於子字串的數目,則會傳回可用的子字串,而且不會擲回任何例外狀況。If count is greater than the number of substrings, the available substrings are returned and no exception is thrown.

下表提供範例。The following table provides examples.

字串值String value SeparatorSeparator CountCount 傳回的陣列Returned array
"42, 12, 19""42, 12, 19" new Char [] {',',' '} (C#)new Char[] {',', ' '} (C#)

Char () = {"," c,"" c} (Visual Basic)Char() = {","c, " "c} (Visual Basic)
22 {"42", " 12, 19"}{"42", " 12, 19"}
"42..12..19""42..12..19" new Char [] {'. '}new Char[] {'.'} (C#)(C#)

Char () = {"."c} (Visual Basic)Char() = {"."c} (Visual Basic)
44 {"42", "", "12", ".19"}{"42", "", "12", ".19"}
香蕉"Banana" new Char [] {'. '}new Char[] {'.'} (C#)(C#)

Char () = {"."c} (Visual Basic)Char() = {"."c} (Visual Basic)
22 {"香蕉"}{"Banana"}
"Darb\nSmarba" (C#)"Darb\nSmarba" (C#)

"Darb" & vbLf & "Smarba" (Visual Basic)"Darb" & vbLf & "Smarba" (Visual Basic)
new Char [] {} (C#)new Char[] {} (C#)

Char () = {} (Visual Basic)Char() = {} (Visual Basic)
11 {"Darb\nSmarba"}(C#){"Darb\nSmarba"} (C#)

"Darb" & vbLf & "Smarba" (Visual Basic)"Darb" & vbLf & "Smarba" (Visual Basic)
"Darb\nSmarba" (C#)"Darb\nSmarba" (C#)

"Darb" & vbLf & "Smarba" (Visual Basic)"Darb" & vbLf & "Smarba" (Visual Basic)
new Char [] null (C#)new Char[] null (C#)

Char () = 無Char() = Nothing
22 {"Darb", "Smarba"}{"Darb", "Smarba"}
"Darb\nSmarba" (C#)"Darb\nSmarba" (C#)

"Darb" & vbLf & "Smarba" (Visual Basic)"Darb" & vbLf & "Smarba" (Visual Basic)
new Char [] null (C#)new Char[] null (C#)

Char () = 無Char() = Nothing
100100 {"Darb", "Smarba"}{"Darb", "Smarba"}

效能考量Performance Considerations

方法會為傳回的陣列物件String和每個陣列元素的物件配置記憶體。 SplitThe Split methods allocate memory for the returned array object and a String object for each array element. 如果您的應用程式需要最佳效能,或是在您的應用程式中管理記憶體配置非常IndexOf重要IndexOfAny ,請考慮使用或Compare方法,並選擇性地選擇方法,以在字串中尋找子字串。If your application requires optimal performance or if managing memory allocation is critical in your application, consider using the IndexOf or IndexOfAny method, and optionally the Compare method, to locate a substring within a string.

如果您要在分隔字元處分割字串,請使用IndexOfIndexOfAny方法來尋找字串中的分隔符號。If you are splitting a string at a separator character, use the IndexOf or IndexOfAny method to locate a separator character in the string. 如果您要在分隔符號字串處分割字串,請使用IndexOfIndexOfAny方法來尋找分隔符號字串的第一個字元。If you are splitting a string at a separator string, use the IndexOf or IndexOfAny method to locate the first character of the separator string. 然後使用Compare方法來判斷第一個字元之後的字元是否等於分隔符號字串的其餘字元。Then use the Compare method to determine whether the characters after that first character are equal to the remaining characters of the separator string.

此外,如果使用同一組字元來分割多個Split方法呼叫中的字串,請考慮建立單一陣列,並在每個方法呼叫中參考它。In addition, if the same set of characters is used to split strings in multiple Split method calls, consider creating a single array and referencing it in each method call. 這會大幅降低每個方法呼叫的額外負荷。This significantly reduces the additional overhead of each method call.

給呼叫者的注意事項

Trim(Char[]) null separator在和舊版中, Split(Char[])如果傳遞的方法是或不包含任何字元,則方法會使用稍微不同的字元集來分割字串,而不是方法所做的.NET Framework 3.5.NET Framework 3.5修剪字串。In the .NET Framework 3.5.NET Framework 3.5 and earlier versions, if the Split(Char[]) method is passed a separator that is null or contains no characters, the method uses a slightly different set of characters to split the string than the Trim(Char[]) method does to trim the string. 從 .NET Framework 4 開始,這兩種方法都會使用一組相同的 Unicode 空白字元。Starting with the .NET Framework 4, both methods use an identical set of Unicode white-space characters.

另請參閱

Split(Char, StringSplitOptions) Split(Char, StringSplitOptions) 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 Char Char Char

傳回

String[]

Split(String, StringSplitOptions) Split(String, StringSplitOptions) Split(String, StringSplitOptions)

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

參數

傳回

String[]

Split(Char[]) Split(Char[]) Split(Char[]) Split(Char[])

根據陣列中的字元分割字串成子字串。Splits a string into substrings that are based on the characters in an array.

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

參數

separator
Char[]

字串陣列 (可分隔這個字串中的子字串)、不含任何分隔符號的空陣列,或 nullA character array that delimits the substrings in this string, an empty array that contains no delimiters, or null.

傳回

String[]

陣列,其項目中包含了這個執行個體中的子字串,由 separator 內的一或多個字元分隔。An array whose elements contain the substrings from this instance that are delimited by one or more characters in separator. 如需詳細資訊,請參閱<備註>一節。For more information, see the Remarks section.

範例

下列範例示範如何藉由將空白字元和標點符號視為分隔符號,從文字塊中解壓縮個別單字。The following example demonstrates how to extract individual words from a block of text by treating white space and punctuation marks as delimiters. 傳遞至separator String.Split(Char[])方法之參數的字元陣列包含空白字元和定位字元,以及一些常見的標點符號符號。The character array passed to the separator parameter of the String.Split(Char[]) method consists of a space character and a tab character, together with some common punctuation symbols.

string words = "This is a list of words, with: a bit of punctuation" +
               "\tand a tab character.";

string [] split = words.Split(new Char [] {' ', ',', '.', ':', '\t' });

foreach (string s in split) 
{

    if (s.Trim() != "")
        Console.WriteLine(s);
}

// The example displays the following output to the console:
//       This
//       is
//       a
//       list
//       of
//       words
//       with
//       a
//       bit
//       of
//       punctuation
//       and
//       a
//       tab
//       character
Public Class SplitTest
    Public Shared Sub Main()
        Dim words As String = "This is a list of words, with: a bit of punctuation" + _
                              vbTab + "and a tab character."
        Dim split As String() = words.Split(New [Char]() {" "c, ","c, "."c, ":"c, CChar(vbTab) })
                
        For Each s As String In  split
            If s.Trim() <> "" Then
                Console.WriteLine(s)
            End If
        Next s
    End Sub
End Class 'SplitTest
' The example displays the following output to the console:
'       This
'       is
'       a
'       list
'       of
'       words
'       with
'       a
'       bit
'       of
'       punctuation
'       and
'       a
'       tab
'       character

備註

當字串以一組已知的字元分隔時,您可以使用Split(Char[])方法,將它分隔成子字串。When a string is delimited by a known set of characters, you can use the Split(Char[]) method to separate it into substrings.

傳回值詳細資料Return value details

分隔符號不會包含在傳回之陣列的元素中。Delimiter characters are not included in the elements of the returned array. 例如,如果分隔符號陣列包含字元 "-",而目前字串實例的值是 "aa-bb-cc",則方法會傳回包含三個元素的陣列: "aa"、"bb" 和 "cc"。For example, if the separator array includes the character "-" and the value of the current string instance is "aa-bb-cc", the method returns an array that contains three elements: "aa", "bb", and "cc".

如果這個實例不包含中separator的任何字元,則傳回的陣列會由包含這個實例的單一元素所組成。If this instance does not contain any of the characters in separator, the returned array consists of a single element that contains this instance.

separator每個元素都會定義個別的分隔符號。Each element of separator defines a separate delimiter character. 如果兩個分隔符號相鄰,或在這個實例的開頭或結尾找到分隔符號,則傳回陣列中的對應元素會包含EmptyIf two delimiters are adjacent, or a delimiter is found at the beginning or end of this instance, the corresponding element in the returned array contains Empty. 以下是一些範例:Here are some examples:

字串值String value SeparatorSeparator 傳回的陣列Returned array
"42, 12, 19""42, 12, 19" new Char [] {',',' '} (C#)new Char[] {',', ' '} (C#)

Char () = {"," c,"" c})(Visual Basic)Char() = {","c, " "c}) (Visual Basic)
{"42", "", "12", "", "19"}{"42", "", "12", "", "19"}
"42..12..19""42..12..19" new Char [] {'. '}new Char[] {'.'} (C#)(C#)

Char () = {"."c} (Visual Basic)Char() = {"."c} (Visual Basic)
{"42", "", "12", "", "19"}{"42", "", "12", "", "19"}
香蕉"Banana" new Char [] {'. '}new Char[] {'.'} (C#)(C#)

Char () = {"."c} (Visual Basic)Char() = {"."c} (Visual Basic)
{"香蕉"}{"Banana"}
"Darb\nSmarba" (C#)"Darb\nSmarba" (C#)

"Darb" & vbLf & "Smarba" (Visual Basic)"Darb" & vbLf & "Smarba" (Visual Basic)
new Char [] {} (C#)new Char[] {} (C#)

Char () = {} (Visual Basic)Char() = {} (Visual Basic)
{"Darb", "Smarba"}{"Darb", "Smarba"}
"Darb\nSmarba" (C#)"Darb\nSmarba" (C#)

"Darb" & vbLf & "Smarba" (Visual Basic)"Darb" & vbLf & "Smarba" (Visual Basic)
null (C#)null (C#)

Nothing (Visual Basic)Nothing (Visual Basic)
{"Darb", "Smarba"}{"Darb", "Smarba"}

分隔符號陣列The separator array

分隔符號的每個元素都會定義個別的分隔符號,其中包含單一字元。Each element of separator defines a separate delimiter that consists of a single character. 如果引數是null或不包含任何字元,則方法會將空白字元視為分隔符號。 separatorIf the separator argument is null or contains no characters, the method treats white-space characters as the delimiters. 空白字元是由 Unicode 標準所定義;true如果傳遞Char.IsWhiteSpace至方法,則會傳回。White-space characters are defined by the Unicode standard; they return true if they are passed to the Char.IsWhiteSpace method.

字串. Split (Char [])和編譯器多載解析String.Split(Char[]) and compiler overload resolution

雖然的這個多載的String.Split單一參數是字元陣列,但是您可以使用單一字元來呼叫它,如下列範例所示。Although the single parameter for this overload of String.Split is a character array, you can call it with a single character, as the following example shows.

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.
Module Example
   Public Sub Main()
      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
End Module
' The example displays the following output:
'     Thi
'      i
'      a
'     hort
'     tring.

因為參數是ParamArrayAttribute以屬性裝飾,所以編譯器會將單一字元解讀為單一元素字元陣列。 separatorBecause the separator parameter is decorated with the ParamArrayAttribute attribute, compilers will interpret a single character as a single-element character array. 這不是separator包含參數的其他String.Split多載的情況; 您必須明確地將字元陣列separator當做引數傳遞給這些多載。This is not the case for other String.Split overloads that include a separator parameter; you must explicitly pass these overloads a character array as the separator argument.

比較詳細資料Comparison details

方法會將這個字串中的子字串,以separator陣列中的一或多個字元分隔,並傳回這些子字串做為陣列的元素。 Split(Char[])The Split(Char[]) method extracts the substrings in this string that are delimited by one or more of the characters in the separator array, and returns those substrings as elements of an array.

Split(Char[])方法會使用區分大小寫的序數排序規則來執行比較,藉以尋找分隔符號。The Split(Char[]) method looks for delimiters by performing comparisons using case-sensitive ordinal sort rules. 如需有關 word、string 和序數排序的詳細資訊,請System.Globalization.CompareOptions參閱列舉。For more information about word, string, and ordinal sorts, see the System.Globalization.CompareOptions enumeration.

效能考量Performance Considerations

方法會為傳回的陣列物件String和每個陣列元素的物件配置記憶體。 SplitThe Split methods allocate memory for the returned array object and a String object for each array element. 如果您的應用程式需要最佳效能,或是在您的應用程式中管理記憶體配置非常IndexOf重要IndexOfAny ,請考慮使用或方法。If your application requires optimal performance or if managing memory allocation is critical in your application, consider using the IndexOf or IndexOfAny method. 您也可以選擇使用Compare方法,在字串中尋找子字串。You also have the option of using the Compare method to locate a substring within a string.

若要在分隔符號處分割字串,請使用IndexOfIndexOfAny方法來尋找字串中的分隔符號。To split a string at a separator character, use the IndexOf or IndexOfAny method to locate a separator character in the string. 若要在分隔符號字串上分割字串,請使用IndexOfIndexOfAny方法來尋找分隔符號字串的第一個字元。To split a string at a separator string, use the IndexOf or IndexOfAny method to locate the first character of the separator string. 然後使用Compare方法來判斷第一個字元之後的字元是否等於分隔符號字串的其餘字元。Then use the Compare method to determine whether the characters after that first character are equal to the remaining characters of the separator string.

此外,如果使用同一組字元來分割多個Split方法呼叫中的字串,請考慮建立單一陣列,並在每個方法呼叫中參考它。In addition, if the same set of characters is used to split strings in multiple Split method calls, consider creating a single array and referencing it in each method call. 這會大幅降低每個方法呼叫的額外負荷。This significantly reduces the additional overhead of each method call.

給呼叫者的注意事項

Trim(Char[]) null separator在和舊版中, Split(Char[])如果傳遞的方法是或不包含任何字元,則方法會使用稍微不同的字元集來分割字串,而不是方法所做的.NET Framework 3.5.NET Framework 3.5修剪字串。In the .NET Framework 3.5.NET Framework 3.5 and earlier versions, if the Split(Char[]) method is passed a separator that is null or contains no characters, the method uses a slightly different set of characters to split the string than the Trim(Char[]) method does to trim the string. 從 .NET Framework 4 開始,這兩種方法都會使用一組相同的 Unicode 空白字元。Starting with the .NET Framework 4, both methods use an identical set of Unicode white-space characters.

另請參閱

適用於