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 specified delimiting characters and, optionally, options.

Split(Char, Int32, StringSplitOptions)

基于指定的分隔字符和(可选)选项将字符串拆分为最大数量的子字符串。Splits a string into a maximum number of substrings based on a specified delimiting character and, optionally, options. 根据提供的字符分隔符将字符串拆分为最大数量的子字符串,可以选择忽略结果中的空子字符串。Splits a string into a maximum number of substrings based on the provided character separator, optionally omitting empty substrings from the result.

Split(String[], Int32, StringSplitOptions)

基于指定的分隔字符串和(可选)选项将字符串拆分为最大数量的子字符串。Splits a string into a maximum number of substrings based on specified delimiting strings and, optionally, options.

Split(String[], StringSplitOptions)

基于指定的分隔字符串和(可选)选项将字符串拆分为子字符串。Splits a string into substrings based on a specified delimiting string and, optionally, options.

Split(String, Int32, StringSplitOptions)

基于指定的分隔字符串和(可选)选项将字符串拆分为最大数量的子字符串。Splits a string into a maximum number of substrings based on a specified delimiting string and, optionally, options.

Split(Char[], StringSplitOptions)

根据指定的分隔字符和选项将字符串拆分为子字符串。Splits a string into substrings based on specified delimiting characters and options.

Split(Char[], Int32)

根据指定的分隔字符将一个字符串拆分成最大数量的子字符串。Splits a string into a maximum number of substrings based on specified delimiting characters.

Split(Char, StringSplitOptions)

基于指定的分隔字符和(可选)选项将字符串拆分为子字符串。Splits a string into substrings based on a specified delimiting character and, optionally, options.

Split(String, StringSplitOptions)

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

Split(Char[])

根据指定的分隔字符将字符串拆分为子字符串。Splits a string into substrings based on specified delimiting characters.

注解

Split 用于将分隔的字符串拆分为子字符串。Split is used to break a delimited string into substrings. 您可以使用字符数组或字符串数组来指定零个或多个分隔字符或字符串。You can use either a character array or a string array to specify zero or more delimiting characters or strings. 如果未指定任何分隔字符,则将字符串拆分为空白字符。If no delimiting characters are specified, the string is split at white-space characters.

使用方法的重载 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 specify whether to include empty strings and/or trim substrings in the result (the Split(Char[], StringSplitOptions) and Split(String[], StringSplitOptions) methods), or to do both (the Split(Char[], Int32, StringSplitOptions) and Split(String[], Int32, StringSplitOptions) methods).

提示

Split方法并非总是将分隔的字符串拆分为子字符串的最佳方式。The Split method is not always the best way to break a delimited string into substrings. 如果您不希望提取分隔字符串的所有子字符串,或者您想要基于某个模式(而不是一组分隔符字符)分析字符串,请考虑使用正则表达式,或将使用方法返回字符索引的搜索方法之一组合起来 SubstringIf 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 using regular expressions, or combine one of the search methods that returns the index of a character with the Substring method. 有关详细信息,请参阅 从字符串中提取子字符串。For more information, see Extract substrings from a string.

示例Example

下面的示例显示了三种不同的 String.Split() 重载。The following examples show three different overloads of String.Split(). 第一个示例调用 Split(Char[]) 重载,并传入单个分隔符。The first example calls the Split(Char[]) overload and passes in a single delimiter.

string s = "You win some. You lose some.";

string[] subs = s.Split(' ');

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

// This example produces the following output:
//
// Substring: You
// Substring: win
// Substring: some.
// Substring: You
// Substring: lose
// Substring: some.
Dim s As String = "You win some. You lose some."
Dim subs As String() = s.Split()

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

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

正如你所看到的那样,两个子字符串之间包含句点字符 (.)。As you can see, the period characters (.) are included in two of the substrings. 如果要排除句点字符,可以将句点字符添加为额外的分隔符。If you want to exclude the period characters, you can add the period character as an additional delimiting character. 下面的示例演示了如何执行此操作。The next example shows how to do this.

string s = "You win some. You lose some.";

string[] subs = s.Split(' ', '.');

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

// This example produces the following output:
//
// Substring: You
// Substring: win
// Substring: some
// Substring:
// Substring: You
// Substring: lose
// Substring: some
// Substring:
Dim s As String = "You win some. You lose some."
Dim subs As String() = s.Split(" "c, "."c)

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

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

子字符串之间的句点消息,但现在包含了两个额外的空子字符串。The periods are gone from the substrings, but now two extra empty substrings have been included. 这些空子字符串表示单词与其后的句点之间的子字符串。These empty substring represent the substring between a word and the period that follows it. 若要从生成的数组中删除空字符串,可以调用 Split(Char[], StringSplitOptions) 重载,并为 options 参数指定 StringSplitOptions.RemoveEmptyEntriesTo omit empty substrings from the resulting array, you can call the Split(Char[], StringSplitOptions) overload and specify StringSplitOptions.RemoveEmptyEntries for the options parameter.

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

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

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

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

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

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

各个重载的部分 String.Split() 包含进一步的示例。The sections for the individual overloads of String.Split() contain further examples.

Split(Char[], Int32, StringSplitOptions)

基于指定的分隔字符和(可选)选项将字符串拆分为最大数量的子字符串。Splits a string into a maximum number of substrings based on specified delimiting characters and, optionally, options.

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

参数

separator
Char[]

分隔此字符串中子字符串的字符数组、不包含分隔符的空数组或 nullAn array of characters that delimit 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

枚举值的按位组合,用于指定是否剪裁子字符串并包含空子字符串。A bitwise combination of the enumeration values that specifies whether to trim substrings and include empty substrings.

返回

String[]

一个数组,该数组包含此字符串中的子字符串,这些子字符串由 separator 中的一个或多个字符分隔。An array that contains 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 枚举来包括或排除方法生成的子字符串 SplitThe 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.Split() methods that use
// the StringSplitOptions enumeration.
string s1 = ",ONE,,TWO,,,THREE,,";
string s2 = "[stop]" +
            "ONE[stop][stop]" +
            "TWO[stop][stop][stop]" +
            "THREE[stop][stop]";
char[] charSeparators = new char[] { ',' };
string[] stringSeparators = new string[] { "[stop]" };
string[] result;
// ------------------------------------------------------------------------------
// Split a string delimited by characters.
// ------------------------------------------------------------------------------
Console.WriteLine("1) Split a string delimited by characters:\n");

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

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

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

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

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

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

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

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

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

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

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

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

/*
This example produces the following results:

1) Split a string delimited by characters:

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

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

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

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

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

2) Split a string delimited by another string:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

End Sub


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

End Sub

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

注解

分隔符字符不包含在返回数组的元素中。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 true 如果传递给它,则方法将返回。White-space characters are defined by the Unicode standard and the Char.IsWhiteSpace method returns true if they are passed to it. 但是,如果对 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";

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

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

_ = 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 ,并且在返回值的最后一个元素中返回此实例中剩余的字符。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[]) 方法传递的 separatornull 或不包含任何字符,则该方法将使用一组略微不同的空白字符来拆分字符串,而不是使用 Trim(Char[]) 方法来剪裁字符串。In .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 white-space characters to split the string than the Trim(Char[]) method does to trim the string. 从 .NET Framework 4 开始,这两个方法都使用一组相同的 Unicode 空白字符。Starting with .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 of substrings based on a specified delimiting character and, optionally, options. 根据提供的字符分隔符将字符串拆分为最大数量的子字符串,可以选择忽略结果中的空子字符串。Splits a string into a maximum number of substrings based on the provided character separator, optionally omitting empty substrings from the result.

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

枚举值的按位组合,用于指定是否剪裁子字符串并包含空子字符串。A bitwise combination of the enumeration values that specifies whether to trim substrings and include empty substrings.

返回

String[]

一个数组,该数组包含此实例中的至多 count 个子字符串,这些子字符串由 separator 分隔。An array that contains 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 specified delimiting strings and, optionally, options.

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

参数

separator
String[]

分隔此字符串中子字符串的字符串、不包含分隔符的空数组或 nullThe strings that delimit 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

枚举值的按位组合,用于指定是否剪裁子字符串并包含空子字符串。A bitwise combination of the enumeration values that specifies whether to trim substrings and include empty substrings.

返回

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 枚举来包括或排除方法生成的子字符串 SplitThe 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.Split() methods that use
// the StringSplitOptions enumeration.
string s1 = ",ONE,,TWO,,,THREE,,";
string s2 = "[stop]" +
            "ONE[stop][stop]" +
            "TWO[stop][stop][stop]" +
            "THREE[stop][stop]";
char[] charSeparators = new char[] { ',' };
string[] stringSeparators = new string[] { "[stop]" };
string[] result;
// ------------------------------------------------------------------------------
// Split a string delimited by characters.
// ------------------------------------------------------------------------------
Console.WriteLine("1) Split a string delimited by characters:\n");

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

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

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

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

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

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

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

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

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

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

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

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

/*
This example produces the following results:

1) Split a string delimited by characters:

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

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

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

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

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

2) Split a string delimited by another string:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

End Sub


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

End Sub

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

注解

分隔符字符串不包含在返回数组的元素中。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 true 如果传递给它,则方法将返回。White-space characters are defined by the Unicode standard and the Char.IsWhiteSpace method returns true if they are passed to it. 但是,如果对 separator 此方法重载的调用中的参数为 null ,则编译器重载决策失败。However, if the separator parameter in the call to this method overload is null, compiler overload resolution fails. 为了明确标识所调用的方法,你的代码必须指示的类型 nullTo 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";

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

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

_ = 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 ,并且在返回值的最后一个元素中返回此实例中剩余的字符。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方法将忽略 separator 其值为 null 或空字符串 ( "" ) 的任何元素。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. 实例中的子字符串的出现顺序优先于中元素的顺序 separatorThe 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" 中的子字符串,并与中的元素匹配 separatorThis 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[]) 方法传递的 separatornull 或不包含任何字符,则该方法将使用一组略微不同的空白字符来拆分字符串,而不是使用 Trim(Char[]) 方法来剪裁字符串。In .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 white-space characters to split the string than the Trim(Char[]) method does to trim the string. 从 .NET Framework 4 开始,这两个方法都使用一组相同的 Unicode 空白字符。Starting with .NET Framework 4, both methods use an identical set of Unicode white-space characters.

适用于

Split(String[], StringSplitOptions)

基于指定的分隔字符串和(可选)选项将字符串拆分为子字符串。Splits a string into substrings based on a specified delimiting string and, optionally, options.

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

参数

separator
String[]

分隔此字符串中子字符串的字符串数组、不包含分隔符的空数组或 nullAn array of strings that delimit the substrings in this string, an empty array that contains no delimiters, or null.

options
StringSplitOptions

枚举值的按位组合,用于指定是否剪裁子字符串并包含空子字符串。A bitwise combination of the enumeration values that specifies whether to trim substrings and include empty substrings.

返回

String[]

一个数组,其元素包含此字符串中的子字符串,这些子字符串由 separator 中的一个或多个字符串分隔。An array whose elements contain the substrings in this string that are delimited by one or more strings in separator. 有关详细信息,请参阅“备注”部分。For more information, see the Remarks section.

属性

例外

options 不是 StringSplitOptions 值之一。options is not one of the StringSplitOptions values.

示例

下面的示例说明了通过调用字符串的 String.Split(String[], StringSplitOptions) 方法(其 options 参数等于和)返回的数组中的 StringSplitOptions.None 差异 StringSplitOptions.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   \"{source}\".");
Console.WriteLine();
Console.WriteLine($"Using the delimiter string:\n   \"{stringSeparators[0]}\"");
Console.WriteLine();

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

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

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

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

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

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

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

下面的示例定义一个包含标点和空白字符的分隔符数组。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
    Dim separators() As String = {",", ".", "!", "?", ";", ":", " "}
    Dim value As String = "The handsome, energetic, young dog was playing with his smaller, more lethargic litter mate."
    Dim words() As String = value.Split(separators, StringSplitOptions.RemoveEmptyEntries)
    For Each word In words
        Console.WriteLine(word)
    Next
End Sub

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

请注意,在参数设置为的情况下调用方法 options StringSplitOptions.RemoveEmptyEntriesNote 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.

分隔符字符串不包含在返回数组的元素中。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- _ ",而参数的值 optionsNone ,则该方法返回一个字符串数组,其中包含以下五个元素: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 non-empty strings, white-space characters are assumed to be the delimiters. 空白字符由 Unicode 标准定义, Char.IsWhiteSpace true 如果传递给它,则方法将返回。White-space characters are defined by the Unicode standard and the Char.IsWhiteSpace method returns true if they are passed to it.

如果 separator 调用此方法重载的中的参数为 null ,则编译器重载决策失败。If the separator parameter in the call to this method overload is null, compiler overload resolution fails. 为了明确标识所调用的方法,你的代码必须指示的类型 nullTo 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";

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

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

_ = 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方法将忽略 separator 其值为 null 或空字符串 ( "" ) 的任何元素。The Split method ignores any element of separator whose value is null or the empty string ("").

若要在中的字符串具有相同的字符时避免出现不明确的结果, separatorSplit 操作将从实例值的开头开始,并与中的第一个元素( 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. 实例中的子字符串的出现顺序优先于中元素的顺序 separatorThe 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" 中的子字符串,并与中的元素匹配 separatorThis 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[]) 方法传递的 separatornull 或不包含任何字符,则该方法将使用一组略微不同的空白字符来拆分字符串,而不是使用 Trim(Char[]) 方法来剪裁字符串。In .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 white-space characters to split the string than the Trim(Char[]) method does to trim the string. 从 .NET Framework 4 开始,这两个方法都使用一组相同的 Unicode 空白字符。Starting with .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 a specified delimiting string and, optionally, options.

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

参数

separator
String

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

count
Int32

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

options
StringSplitOptions

枚举值的按位组合,用于指定是否剪裁子字符串并包含空子字符串。A bitwise combination of the enumeration values that specifies whether to trim substrings and include empty substrings.

返回

String[]

一个数组,该数组包含此实例中的至多 count 个子字符串,这些子字符串由 separator 分隔。An array that contains 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 specified delimiting characters and options.

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

参数

separator
Char[]

分隔此字符串中子字符串的字符数组、不包含分隔符的空数组或 nullAn array of characters that delimit the substrings in this string, an empty array that contains no delimiters, or null.

options
StringSplitOptions

枚举值的按位组合,用于指定是否剪裁子字符串并包含空子字符串。A bitwise combination of the enumeration values that specifies whether to trim substrings and include empty substrings.

返回

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 枚举来包括或排除方法生成的子字符串 SplitThe 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.Split() methods that use
// the StringSplitOptions enumeration.
string s1 = ",ONE,,TWO,,,THREE,,";
string s2 = "[stop]" +
            "ONE[stop][stop]" +
            "TWO[stop][stop][stop]" +
            "THREE[stop][stop]";
char[] charSeparators = new char[] { ',' };
string[] stringSeparators = new string[] { "[stop]" };
string[] result;
// ------------------------------------------------------------------------------
// Split a string delimited by characters.
// ------------------------------------------------------------------------------
Console.WriteLine("1) Split a string delimited by characters:\n");

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

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

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

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

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

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

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

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

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

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

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

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

/*
This example produces the following results:

1) Split a string delimited by characters:

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

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

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

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

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

2) Split a string delimited by another string:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

End Sub


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

End Sub

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

注解

分隔符字符 (数组中的字符 separator) 不包含在返回数组的元素中。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- _ ",而参数的值 optionsNone ,则该方法返回一个字符串数组,其中包含以下五个元素: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 true 如果传递给它,则方法将返回。White-space characters are defined by the Unicode standard and the Char.IsWhiteSpace method returns true if they are passed to it.

如果 separator 参数为 null ,则编译器重载决策失败。If the separator parameter is null, compiler overload resolution fails. 为了明确标识所调用的方法,你的代码必须指示的类型 nullTo 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";

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

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

_ = 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[]) 方法传递的 separatornull 或不包含任何字符,则该方法将使用一组略微不同的空白字符来拆分字符串,而不是使用 Trim(Char[]) 方法来剪裁字符串。In .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 white-space characters to split the string than the Trim(Char[]) method does to trim the string. 从 .NET Framework 4 开始,这两个方法都使用一组相同的 Unicode 空白字符。Starting with .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 specified delimiting characters.

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

参数

separator
Char[]

分隔此字符串中子字符串的字符数组、不包含分隔符的空数组或 nullAn array of characters that delimit 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 使用来限制返回的字符串的数目 SplitThe following example demonstrates how count can be used to limit the number of strings returned by Split.

string name = "Alex Johnson III";

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

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

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

Dim substrings = name.Split(Nothing, 2)
Dim firstName As String = substrings(0)
Dim lastName As String

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

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

注解

分隔符字符不包含在返回数组的元素中。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 true 如果传递给它,则方法将返回。White-space characters are defined by the Unicode standard and the Char.IsWhiteSpace method returns true if they are passed to it.

的每个元素 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 - 1 substrings are returned in the first count - 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 shows some examples.

语言Language 字符串值String value SeparatorSeparator 返回数组Returned array
C#C# "42, 12, 19""42, 12, 19" new Char [] {",",""}new Char[] {',', ' '} {"42", "", "12", "", "19"}{"42", "", "12", "", "19"}
Visual BasicVisual Basic "42, 12, 19""42, 12, 19" Char ( # A1 = {"," c,"" c} ) Char() = {","c, " "c}) {"42", "", "12", "", "19"}{"42", "", "12", "", "19"}
C#C# "42. 12 ... 19.""42..12..19." new Char [] {"."}new Char[] {'.'} {"42","","12","","19",""}{"42", "", "12", "", "19", ""}
Visual BasicVisual Basic "42. 12 ... 19.""42..12..19." Char ( # A1 = {"."ansi-cChar() = {"."c} {"42","","12","","19",""}{"42", "", "12", "", "19", ""}
C#C# 香蕉"Banana" new Char [] {"."}new Char[] {'.'} {"香蕉"}{"Banana"}
Visual BasicVisual Basic 香蕉"Banana" Char ( # A1 = {"."ansi-cChar() = {"."c} {"香蕉"}{"Banana"}
C#C# "Darb\nSmarba""Darb\nSmarba" new Char [] {}new Char[] {} {"Darb", "Smarba"}{"Darb", "Smarba"}
Visual BasicVisual Basic "Darb" & vbLf & "Smarba""Darb" & vbLf & "Smarba" Char ( # A1 = {}Char() = {} {"Darb", "Smarba"}{"Darb", "Smarba"}
C#C# "Darb\nSmarba""Darb\nSmarba" Nullnull {"Darb", "Smarba"}{"Darb", "Smarba"}
Visual BasicVisual Basic "Darb" & vbLf & "Smarba""Darb" & vbLf & "Smarba" Nothing {"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[]) 方法传递的 separatornull 或不包含任何字符,则该方法将使用一组略微不同的空白字符来拆分字符串,而不是使用 Trim(Char[]) 方法来剪裁字符串。In .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 white-space characters to split the string than the Trim(Char[]) method does to trim the string. 从 .NET Framework 4 开始,这两个方法都使用一组相同的 Unicode 空白字符。Starting with .NET Framework 4, both methods use an identical set of Unicode white-space characters.

另请参阅

适用于

Split(Char, StringSplitOptions)

基于指定的分隔字符和(可选)选项将字符串拆分为子字符串。Splits a string into substrings based on a specified delimiting character and, optionally, options.

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

枚举值的按位组合,用于指定是否剪裁子字符串并包含空子字符串。A bitwise combination of the enumeration values that specifies whether to trim substrings and include empty substrings.

返回

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

枚举值的按位组合,用于指定是否剪裁子字符串并包含空子字符串。A bitwise combination of the enumeration values that specifies whether to trim substrings and include empty substrings.

返回

String[]

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

适用于

Split(Char[])

根据指定的分隔字符将字符串拆分为子字符串。Splits a string into substrings based on specified delimiting characters.

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

参数

separator
Char[]

分隔字符的数组、不包含分隔符的空数组或 nullAn array of delimiting characters, 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.

示例

下面的示例演示了如何通过将空格字符 ( ) 和制表符 (\t) 作为分隔符来从文本块提取各个单词。The following example demonstrates how to extract individual words from a block of text by treating the space character ( ) and tab character (\t) as delimiters. 要拆分的字符串同时包含这两个字符。The string being split includes both of these characters.

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

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

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

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

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

注解

当使用一组已知的字符分隔字符串时,可以使用 Split(Char[]) 方法将其分隔为子字符串。When a string is delimited by a known set of characters, you can use the Split(Char[]) method to separate it into substrings.

分隔符字符不包含在返回数组的元素中。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.

下表显示了一些示例。The following table shows some examples.

语言Language 字符串值String value SeparatorSeparator 返回数组Returned array
C#C# "42, 12, 19""42, 12, 19" new Char [] {",",""}new Char[] {',', ' '} {"42", "", "12", "", "19"}{"42", "", "12", "", "19"}
Visual BasicVisual Basic "42, 12, 19""42, 12, 19" Char ( # A1 = {"," c,"" c} ) Char() = {","c, " "c}) {"42", "", "12", "", "19"}{"42", "", "12", "", "19"}
C#C# "42. 12 ... 19.""42..12..19." new Char [] {"."}new Char[] {'.'} {"42","","12","","19",""}{"42", "", "12", "", "19", ""}
Visual BasicVisual Basic "42. 12 ... 19.""42..12..19." Char ( # A1 = {"."ansi-cChar() = {"."c} {"42","","12","","19",""}{"42", "", "12", "", "19", ""}
C#C# 香蕉"Banana" new Char [] {"."}new Char[] {'.'} {"香蕉"}{"Banana"}
Visual BasicVisual Basic 香蕉"Banana" Char ( # A1 = {"."ansi-cChar() = {"."c} {"香蕉"}{"Banana"}
C#C# "Darb\nSmarba""Darb\nSmarba" new Char [] {}new Char[] {} {"Darb", "Smarba"}{"Darb", "Smarba"}
Visual BasicVisual Basic "Darb" & vbLf & "Smarba""Darb" & vbLf & "Smarba" Char ( # A1 = {}Char() = {} {"Darb", "Smarba"}{"Darb", "Smarba"}
C#C# "Darb\nSmarba""Darb\nSmarba" Nullnull {"Darb", "Smarba"}{"Darb", "Smarba"}
Visual BasicVisual Basic "Darb" & vbLf & "Smarba""Darb" & vbLf & "Smarba" Nothing {"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 标准定义, Char.IsWhiteSpace true 如果向其传递空白字符,该方法将返回。White-space characters are defined by the Unicode standard, and the Char.IsWhiteSpace method returns true if a white-space character is passed to it.

字符串拆分 (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.
    Dim value As String = "This is a short string."
    Dim delimiter As Char = "s"c
    Dim substrings() As String = value.Split(delimiter)
    For Each substring In substrings
        Console.WriteLine(substring)
    Next
End Sub

' The example displays the following output:
'
'     Thi
'      i
'      a
'     hort
'     tring.

由于 separator 参数使用特性进行修饰 ParamArrayAttribute ,因此编译器会将单个字符解释为单元素字符数组。Because the separator parameter is decorated with the ParamArrayAttribute attribute, compilers will interpret a single character as a single-element character array. 这种情况并非 String.Split 包含参数的其他重载的情况 separator ; 必须以参数形式将字符数组显式传递给这些重载 separatorThis 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[]) 方法传递的 separatornull 或不包含任何字符,则该方法将使用一组略微不同的空白字符来拆分字符串,而不是使用 Trim(Char[]) 方法来剪裁字符串。In .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 white-space characters to split the string than the Trim(Char[]) method does to trim the string. 从 .NET Framework 4 开始,这两个方法都使用一组相同的 Unicode 空白字符。Starting with .NET Framework 4, both methods use an identical set of Unicode white-space characters.

另请参阅

适用于