String.Split 方法

定义

返回的字符串数组包含此实例中的子字符串(由指定字符串或 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)

基于数组中的字符将一个字符串拆分成最大数量的子字符串。Splits a string into a maximum number of substrings based on the characters in an array.

Split(Char, Int32, StringSplitOptions)

根据提供的字符分隔符将字符串拆分为最大数目的子字符串。Splits a string into a maximum number substrings based on the provided character separator.

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)

基于数组中的字符串将字符串拆分为多个子字符串。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)

根据提供的字符串分隔符将字符串拆分为最大数目的子字符串。Splits a string into a maximum number of substrings based on the provided string separator.

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)

基于数组中的字符将一个字符串拆分成最大数量的子字符串。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)

根据提供的字符分隔符将字符串拆分为多个子字符串。Splits a string into substrings based on the provided character separator.

Split(String, StringSplitOptions)

根据提供的字符串分隔符将字符串拆分为多个子字符串。Splits a string into substrings that are based on the provided string separator.

Split(Char[])

基于分隔符数组中的字符将字符串拆分为多个子字符串。Splits a string into substrings that are based on the characters in the separator 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 方法的重载,可以限制方法(Split(Char[], Int32) 方法)返回的子字符串的数目,以确定是否在返回的子字符串(Split(Char[], StringSplitOptions)Split(String[], StringSplitOptions) 方法中包含空字符串)或同时执行这两个操作(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. 例如,如果字符串采用 "number 操作数 number" 格式,则可以使用正则表达式提取并处理字符串的元素。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.

Regex.Split 方法与 String.Split几乎相同,不同之处在于,它根据正则表达式模式而不是固定字符集拆分字符串。The 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)

基于数组中的字符将一个字符串拆分成最大数量的子字符串。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

要返回的子字符串的最大数量。The maximum number of substrings to return.

options
StringSplitOptions

要省略返回的数组中的空数组元素,则为 RemoveEmptyEntries;要包含返回的数组中的空数组元素,则为 NoneRemoveEmptyEntries 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.

属性

异常

count 为负数。count is negative.

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
'
'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. 如果 separator 参数 null 或不包含任何字符,则假定空格字符作为分隔符。If the separator parameter is null or contains no characters, white-space characters are assumed to be the delimiters. 空白字符由 Unicode 标准定义,并在传递给 Char.IsWhiteSpace 方法时返回 trueWhite-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)

如果 count 参数为零,或者 options 参数 RemoveEmptyEntries 并且此实例的长度为零,则返回空数组。If 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. 如果 options 参数 None,并且两个分隔符相邻,或在此实例的开头或结尾找到了分隔符,则对应的数组元素包含 EmptyIf 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 减去1个元素中会返回第一个 count 减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

Split 方法为返回的数组对象分配内存,并为每个数组元素分配 String 对象的内存。The Split methods allocate memory for the returned array object and a String object for each array element. 如果你的应用程序需要最佳性能,或者在你的应用程序中管理内存分配非常重要,请考虑使用 IndexOfIndexOfAny 方法,还可以选择使用 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.

调用方说明

.NET Framework 3.5.NET Framework 3.5 及更早版本中,如果将 Split(Char[]) 方法传递到 null 或不包含任何字符的 separator,则该方法将使用一组略有不同的字符来拆分字符串,而不是 Trim(Char[]) 方法来剪裁字符串。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)

根据提供的字符分隔符将字符串拆分为最大数目的子字符串。Splits a string into a maximum number substrings based on the provided character separator.

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

一个字符,用于分隔此实例中的子字符串。A character that delimits the substrings in this instance.

count
Int32

数组中预期的最大元素数。The maximum number of elements expected in the array.

options
StringSplitOptions

枚举值之一,用于确定拆分操作是否应省略返回值中的空子字符串。One of the enumeration values that determines whether the split operation should omit empty substrings from the return value.

返回

String[]

一个数组,其元素包含此实例中的至多 count 个子字符串,这些子字符串由 separator 分隔。An array whose elements contain at most count substrings from this instance that are delimited by separator.

注解

如果已将该字符串拆分 count-1 次,但尚未到达字符串的末尾,则返回数组中的最后一个字符串将包含此实例的其余尾随子字符串,不会进行相应的维护。If the string has already been split count - 1 times, but the end of the string has not been reached, then the last string in the returned array will contain this instance's remaining trailing substring, untouched.

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

要返回的子字符串的最大数量。The maximum number of substrings to return.

options
StringSplitOptions

要省略返回的数组中的空数组元素,则为 RemoveEmptyEntries;要包含返回的数组中的空数组元素,则为 NoneRemoveEmptyEntries 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.

属性

异常

count 为负数。count is negative.

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
'
'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. 如果 separator 参数 null 或不包含任何字符,则假定空格字符作为分隔符。If the separator parameter is null or contains no characters, white-space characters are assumed to be the delimiters. 空白字符由 Unicode 标准定义,并在传递给 Char.IsWhiteSpace 方法时返回 trueWhite-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)

如果 count 参数为零,或者 options 参数 RemoveEmptyEntries 并且此实例的长度为零,则返回空数组。If 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. 如果 options 参数 None,并且两个分隔符相邻,或在此实例的开头或结尾找到了分隔符,则对应的数组元素包含 EmptyIf 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 减去1个元素中会返回第一个 count 减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

Split 方法提取此字符串中的子字符串,这些子字符串由 separator 参数中的一个或多个字符串分隔,并将这些子字符串作为数组的元素返回。The 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、字符串和序号排序的详细信息,请参阅 System.Globalization.CompareOptions 枚举。For more information about word, string, and ordinal sorts, see the System.Globalization.CompareOptions enumeration.

Split 方法将忽略其值为 null 或空字符串("")的 separator 的任何元素。The 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". 这是因为,在遇到子字符串 "f" 之前,遇到了实例 "bcde" 中的子字符串,并与 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

Split 方法为返回的数组对象分配内存,并为每个数组元素分配 String 对象的内存。The Split methods allocate memory for the returned array object and a String object for each array element. 如果你的应用程序需要最佳性能,或者在你的应用程序中管理内存分配非常重要,请考虑使用 IndexOfIndexOfAny 方法,还可以选择使用 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.

调用方说明

.NET Framework 3.5.NET Framework 3.5 及更早版本中,如果将 Split(Char[]) 方法传递到 null 或不包含任何字符的 separator,则该方法将使用一组略有不同的字符来拆分字符串,而不是 Trim(Char[]) 方法来剪裁字符串。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)

基于数组中的字符串将字符串拆分为多个子字符串。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

要省略返回的数组中的空数组元素,则为 RemoveEmptyEntries;要包含返回的数组中的空数组元素,则为 NoneRemoveEmptyEntries 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.NoneStringSplitOptions.RemoveEmptyEntriesThe 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.

如果 options 参数 RemoveEmptyEntries 并且此实例的长度为零,则该方法将返回一个空数组。If 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. 如果 options 参数 None,并且两个分隔符相邻,或在此实例的开头或结尾找到了分隔符,则对应的数组元素包含 String.EmptyIf 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 包括两个元素 "-" 和 "_",则字符串实例的值为 "-_aa-_",options 参数的值为 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." }.}.

如果 separator 参数 null 或不包含任何字符,则假定空格字符作为分隔符。If the separator parameter is null or contains no characters, white-space characters are assumed to be the delimiters. 空白字符由 Unicode 标准定义,并在传递给 Char.IsWhiteSpace 方法时返回 trueWhite-space characters are defined by the Unicode standard and return true if they are passed to the Char.IsWhiteSpace method.

如果 null对此方法重载的调用中的 separator 参数,则编译器重载决策失败。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[]), 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

Split 方法提取此字符串中的子字符串,这些子字符串由 separator 参数中的一个或多个字符串分隔,并将这些子字符串作为数组的元素返回。The 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、字符串和序号排序的详细信息,请参阅 System.Globalization.CompareOptions 枚举。For more information about word, string, and ordinal sorts, see the System.Globalization.CompareOptions enumeration.

Split 方法将忽略其值为 null 或空字符串("")的 separator 的任何元素。The 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". 这是因为,在遇到子字符串 "f" 之前,遇到了实例 "bcde" 中的子字符串,并与 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

Split 方法为返回的数组对象分配内存,并为每个数组元素分配 String 对象的内存。The Split methods allocate memory for the returned array object and a String object for each array element. 如果你的应用程序需要最佳性能,或者在你的应用程序中管理内存分配非常重要,请考虑使用 IndexOfIndexOfAny 方法,还可以选择使用 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.

调用方说明

.NET Framework 3.5.NET Framework 3.5 及更早版本中,如果将 Split(Char[]) 方法传递到 null 或不包含任何字符的 separator,则该方法将使用一组略有不同的字符来拆分字符串,而不是 Trim(Char[]) 方法来剪裁字符串。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)

根据提供的字符串分隔符将字符串拆分为最大数目的子字符串。Splits a string into a maximum number of substrings based on the provided string separator.

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

参数

separator
String

一个字符串,用于分隔此实例中的子字符串。A string that delimits the substrings in this instance.

count
Int32

数组中预期的最大元素数。The maximum number of elements expected in the array.

options
StringSplitOptions

枚举值之一,用于确定拆分操作是否应省略返回值中的空子字符串。One of the enumeration values that determines whether the split operation should omit empty substrings from the return value.

返回

String[]

一个数组,其元素包含此实例中的至多 count 个子字符串,这些子字符串由 separator 分隔。An array whose elements contain at most count substrings from this instance that are delimited by separator.

注解

如果已将该字符串拆分 count-1 次,但尚未到达字符串的末尾,则返回数组中的最后一个字符串将包含此实例的其余尾随子字符串,不会进行相应的维护。If the string has already been split count - 1 times, but the end of the string has not been reached, then the last string in the returned array will contain this instance's remaining trailing substring, untouched.

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

要省略返回的数组中的空数组元素,则为 RemoveEmptyEntries;要包含返回的数组中的空数组元素,则为 NoneRemoveEmptyEntries 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
'
'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.

如果 options 参数 RemoveEmptyEntries 并且此实例的长度为零,则该方法将返回一个空数组。If 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. 如果 options 参数 None,并且两个分隔符相邻,或在此实例的开头或结尾找到了分隔符,则对应的数组元素包含 String.EmptyIf 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 包括两个元素 "-" 和 "_",则字符串实例的值为 "-_aa-_",options 参数的值为 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

如果 separator 参数 null 或不包含任何字符,则假定空格字符作为分隔符。If the separator parameter is null or contains no characters, white-space characters are assumed to be the delimiters. 空白字符由 Unicode 标准定义,并在传递给 Char.IsWhiteSpace 方法时返回 trueWhite-space characters are defined by the Unicode standard and return true if they are passed to the Char.IsWhiteSpace method.

如果 null对此方法重载的调用中的 separator 参数,则编译器重载决策失败。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[]), 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

Split 方法提取此字符串中的子字符串,这些子字符串由 separator 参数中的一个或多个字符分隔,并将这些子字符串作为数组的元素返回。The 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、字符串和序号排序的详细信息,请参阅 System.Globalization.CompareOptions 枚举。For more information about word, string, and ordinal sorts, see the System.Globalization.CompareOptions enumeration.

性能注意事项Performance Considerations

Split 方法为返回的数组对象分配内存,并为每个数组元素分配 String 对象的内存。The Split methods allocate memory for the returned array object and a String object for each array element. 如果你的应用程序需要最佳性能,或者在你的应用程序中管理内存分配非常重要,请考虑使用 IndexOfIndexOfAny 方法,还可以选择使用 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.

调用方说明

.NET Framework 3.5.NET Framework 3.5 及更早版本中,如果将 Split(Char[]) 方法传递到 null 或不包含任何字符的 separator,则该方法将使用一组略有不同的字符来拆分字符串,而不是 Trim(Char[]) 方法来剪裁字符串。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)

基于数组中的字符将一个字符串拆分成最大数量的子字符串。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

要返回的子字符串的最大数量。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 为负数。count is negative.

示例

下面的示例演示 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.

如果 separator 参数 null 或不包含任何字符,则假定空格字符作为分隔符。If the separator parameter is null or contains no characters, white-space characters are assumed to be the delimiters. 空白字符由 Unicode 标准定义,并在传递给 Char.IsWhiteSpace 方法时返回 trueWhite-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 减去1个元素中会返回第一个 count 减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 计数Count 返回数组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 () = NothingChar() = 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 () = NothingChar() = Nothing
100100 {"Darb", "Smarba"}{"Darb", "Smarba"}

性能注意事项Performance Considerations

Split 方法为返回的数组对象分配内存,并为每个数组元素分配 String 对象的内存。The Split methods allocate memory for the returned array object and a String object for each array element. 如果你的应用程序需要最佳性能,或者在你的应用程序中管理内存分配非常重要,请考虑使用 IndexOfIndexOfAny 方法,还可以选择使用 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.

调用方说明

.NET Framework 3.5.NET Framework 3.5 及更早版本中,如果将 Split(Char[]) 方法传递到 null 或不包含任何字符的 separator,则该方法将使用一组略有不同的字符来拆分字符串,而不是 Trim(Char[]) 方法来剪裁字符串。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)

根据提供的字符分隔符将字符串拆分为多个子字符串。Splits a string into substrings based on the provided character separator.

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

一个字符,用于分隔此字符串中的子字符串。A character that delimits the substrings in this string.

options
StringSplitOptions

枚举值之一,用于确定拆分操作是否应省略返回值中的空子字符串。One of the enumeration values that determines whether the split operation should omit empty substrings from the return value.

返回

String[]

一个数组,其元素包含此实例中的子字符串,这些子字符串由 separator 分隔。An array whose elements contain the substrings from this instance that are delimited by separator.

Split(String, StringSplitOptions)

根据提供的字符串分隔符将字符串拆分为多个子字符串。Splits a string into substrings that are based on the provided string separator.

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

参数

separator
String

一个字符串,用于分隔此字符串中的子字符串。A string that delimits the substrings in this string.

options
StringSplitOptions

枚举值之一,用于确定拆分操作是否应省略返回值中的空子字符串。One of the enumeration values that determines whether the split operation should omit empty substrings from the return value.

返回

String[]

一个数组,其元素包含此实例中的子字符串,这些子字符串由 separator 分隔。An array whose elements contain the substrings from this instance that are delimited by separator.

Split(Char[])

基于分隔符数组中的字符将字符串拆分为多个子字符串。Splits a string into substrings that are based on the characters in the separator 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. 传递给 String.Split(Char[]) 方法的 separator 参数的字符数组包含一个空格字符和一个制表符以及一些常用的标点符号。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
' 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. 如果 separator 参数 null 或不包含任何字符,则该方法将空白字符视为分隔符。If 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.

由于 separator 参数使用 ParamArrayAttribute 特性进行修饰,因此编译器会将单个字符解释为单元素字符数组。Because 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

Split(Char[]) 方法提取此字符串中的子字符串,这些子字符串由 separator 数组中的一个或多个字符分隔,并将这些子字符串作为数组的元素返回。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、字符串和序号排序的详细信息,请参阅 System.Globalization.CompareOptions 枚举。For more information about word, string, and ordinal sorts, see the System.Globalization.CompareOptions enumeration.

性能注意事项Performance Considerations

Split 方法为返回的数组对象分配内存,并为每个数组元素分配 String 对象的内存。The Split methods allocate memory for the returned array object and a String object for each array element. 如果你的应用程序需要最佳性能,或者在你的应用程序中管理内存分配非常重要,请考虑使用 IndexOfIndexOfAny 方法。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.

调用方说明

.NET Framework 3.5.NET Framework 3.5 及更早版本中,如果将 Split(Char[]) 方法传递到 null 或不包含任何字符的 separator,则该方法将使用一组略有不同的字符来拆分字符串,而不是 Trim(Char[]) 方法来剪裁字符串。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.

另请参阅

适用于