Разбивает строку на максимальное число подстрок в зависимости от символов в массиве.Splits a string into a maximum number of substrings based on the characters in an array.Можно также указать максимальное число возвращаемых подстрок.You also specify the maximum number of substrings to return.

Альтернативы String. SplitAlternatives to String.Split

Split Метод не всегда является лучшим способом разбивать строку с разделителями на подстроки.The Split method is not always the best way to break a delimited string into substrings.Если вы не хотите извлекать все подстроки из строки с разделителями или хотите проанализировать строку на основе шаблона вместо набора символов-разделителей, рассмотрим следующие варианты.If you don't want to extract all of the substrings of a delimited string, or if you want to parse a string based on a pattern instead of a set of delimiter characters, consider the following alternatives.

Совпадение с одной или несколькими десятичными цифрами.Match one or more decimal digits.Это третья группа записи.This is the third capturing group.

Можно также использовать регулярное выражение для извлечения подстрок из строки на основе шаблона, а не фиксированного набора символов.You can also use a regular expression to extract substrings from a string based on a pattern rather than a fixed set of characters.Это распространенный сценарий, когда происходит одно из следующих условий:This is a common scenario when either of these conditions occurs:

Один или несколько символов-разделителей не всегда являются разделителями в String экземпляре.One or more of the delimiter characters does not always serve as a delimiter in the String instance.

Совпадение с любым символом, который не является открывающей или закрывающей круглой скобкой один или несколько раз.Match any character that is not an opening or a closing bracket one or more times.Это первая группа записи.This is the first capturing group.

Если вы не заинтересованы во всех подстроках в строке, то можете использовать один из методов сравнения строк, возвращающих индекс, с которого начинается сопоставление.If you aren't interested in all of the substrings in a string, you might prefer to work with one of the string comparison methods that returns the index at which the match begins.Затем можно вызвать Substring метод, чтобы извлечь нужную подстроку.You can then call the Substring method to extract the substring that you want.Ниже перечислены методы сравнения строк.The string comparison methods include:

IndexOf, возвращающий Отсчитываемый от нуля индекс первого вхождения символа или строки в экземпляре строки.IndexOf, which returns the zero-based index of the first occurrence of a character or string in a string instance.

IndexOfAny, возвращающий Отсчитываемый от нуля индекс в текущем экземпляре строки первого вхождения любого символа в массиве символов.IndexOfAny, which returns the zero-based index in the current string instance of the first occurrence of any character in a character array.

LastIndexOf, возвращающий Отсчитываемый от нуля индекс последнего вхождения символа или строки в экземпляре строки.LastIndexOf, which returns the zero-based index of the last occurrence of a character or string in a string instance.

LastIndexOfAny, возвращающий Отсчитываемый от нуля индекс в текущем экземпляре строки последнего вхождения любого символа в массиве символов.LastIndexOfAny, which returns a zero-based index in the current string instance of the last occurrence of any character in a character array.

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

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

// This example demonstrates the String() methods that use
// the StringSplitOptions enumeration.
string s1 = ",ONE,,TWO,,,THREE,,";
string s2 = "[stop]" +
"ONE[stop][stop]" +
"TWO[stop][stop][stop]" +
"THREE[stop][stop]";
char[] charSeparators = new char[] {','};
string[] stringSeparators = new string[] {"[stop]"};
string[] result;
// ------------------------------------------------------------------------------
// Split a string delimited by characters.
// ------------------------------------------------------------------------------
Console.WriteLine("1) Split a string delimited by characters:\n");
// Display the original string and delimiter characters.
Console.WriteLine("1a )The original string is \"{0}\".", s1);
Console.WriteLine("The delimiter character is '{0}'.\n",
charSeparators[0]);
// Split a string delimited by characters and return all elements.
Console.WriteLine("1b) Split a string delimited by characters and " +
"return all elements:");
result = s1.Split(charSeparators, StringSplitOptions.None);
Show(result);
// Split a string delimited by characters and return all non-empty elements.
Console.WriteLine("1c) Split a string delimited by characters and " +
"return all non-empty elements:");
result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// Split the original string into the string and empty string before the
// delimiter and the remainder of the original string after the delimiter.
Console.WriteLine("1d) Split a string delimited by characters and " +
"return 2 elements:");
result = s1.Split(charSeparators, 2, StringSplitOptions.None);
Show(result);
// Split the original string into the string after the delimiter and the
// remainder of the original string after the delimiter.
Console.WriteLine("1e) Split a string delimited by characters and " +
"return 2 non-empty elements:");
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// ------------------------------------------------------------------------------
// Split a string delimited by another string.
// ------------------------------------------------------------------------------
Console.WriteLine("2) Split a string delimited by another string:\n");
// Display the original string and delimiter string.
Console.WriteLine("2a) The original string is \"{0}\".", s2);
Console.WriteLine("The delimiter string is \"{0}\".\n", stringSeparators[0]);
// Split a string delimited by another string and return all elements.
Console.WriteLine("2b) Split a string delimited by another string and " +
"return all elements:");
result = s2.Split(stringSeparators, StringSplitOptions.None);
Show(result);
// Split the original string at the delimiter and return all non-empty elements.
Console.WriteLine("2c) Split a string delimited by another string and " +
"return all non-empty elements:");
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// Split the original string into the empty string before the
// delimiter and the remainder of the original string after the delimiter.
Console.WriteLine("2d) Split a string delimited by another string and " +
"return 2 elements:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.None);
Show(result);
// Split the original string into the string after the delimiter and the
// remainder of the original string after the delimiter.
Console.WriteLine("2e) Split a string delimited by another string and " +
"return 2 non-empty elements:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// Display the array of separated strings using a local function
void Show(string[] entries)
{
Console.WriteLine("The return value contains these {0} elements:", entries.Length);
foreach (string entry in entries)
{
Console.Write("<{0}>", entry);
}
Console.Write("\n\n");
}
/*
This example produces the following results:
1) Split a string delimited by characters:
1a )The original string is ",ONE,,TWO,,,THREE,,".
The delimiter character is ','.
1b) Split a string delimited by characters and return all elements:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>
1c) Split a string delimited by characters and return all non-empty elements:
The return value contains these 3 elements:
<ONE><TWO><THREE>
1d) Split a string delimited by characters and return 2 elements:
The return value contains these 2 elements:
<><ONE,,TWO,,,THREE,,>
1e) Split a string delimited by characters and return 2 non-empty elements:
The return value contains these 2 elements:
<ONE><TWO,,,THREE,,>
2) Split a string delimited by another string:
2a) The original string is "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".
The delimiter string is "[stop]".
2b) Split a string delimited by another string and return all elements:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>
2c) Split a string delimited by another string and return all non-empty elements:
The return value contains these 3 elements:
<ONE><TWO><THREE>
2d) Split a string delimited by another string and return 2 elements:
The return value contains these 2 elements:
<><ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]>
2e) Split a string delimited by another string and return 2 non-empty elements:
The return value contains these 2 elements:
<ONE><TWO[stop][stop][stop]THREE[stop][stop]>
*/

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

Комментарии

Символы разделителей не включаются в элементы возвращаемого массива.Delimiter characters are not included in the elements of the returned array.

Если в этом экземпляре count больше подстрок, то первый count минус 1 подстрока возвращается в первые count меньше 1 элементов возвращаемого значения, а остальные символы в этом экземпляре возвращаются в последнем возвращаемого значения.If there are more than count substrings in this instance, the first count minus 1 substrings are returned in the first count minus 1 elements of the return value, and the remaining characters in this instance are returned in the last element of the return value.

Если count больше числа подстрок, возвращаются доступные подстроки и исключение не создается.If count is greater than the number of substrings, the available substrings are returned and no exception is thrown.

При разделении строки на символ-разделитель используйте IndexOf метод или IndexOfAny для нахождение символа разделителя в строке.If you are splitting a string at a separator character, use the IndexOf or IndexOfAny method to locate a separator character in the string.При разделении строки в строке-разделителе используйте IndexOf метод или IndexOfAny для нахождение первого символа строки разделителя.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.

// This example demonstrates the String() methods that use
// the StringSplitOptions enumeration.
string s1 = ",ONE,,TWO,,,THREE,,";
string s2 = "[stop]" +
"ONE[stop][stop]" +
"TWO[stop][stop][stop]" +
"THREE[stop][stop]";
char[] charSeparators = new char[] {','};
string[] stringSeparators = new string[] {"[stop]"};
string[] result;
// ------------------------------------------------------------------------------
// Split a string delimited by characters.
// ------------------------------------------------------------------------------
Console.WriteLine("1) Split a string delimited by characters:\n");
// Display the original string and delimiter characters.
Console.WriteLine("1a )The original string is \"{0}\".", s1);
Console.WriteLine("The delimiter character is '{0}'.\n",
charSeparators[0]);
// Split a string delimited by characters and return all elements.
Console.WriteLine("1b) Split a string delimited by characters and " +
"return all elements:");
result = s1.Split(charSeparators, StringSplitOptions.None);
Show(result);
// Split a string delimited by characters and return all non-empty elements.
Console.WriteLine("1c) Split a string delimited by characters and " +
"return all non-empty elements:");
result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// Split the original string into the string and empty string before the
// delimiter and the remainder of the original string after the delimiter.
Console.WriteLine("1d) Split a string delimited by characters and " +
"return 2 elements:");
result = s1.Split(charSeparators, 2, StringSplitOptions.None);
Show(result);
// Split the original string into the string after the delimiter and the
// remainder of the original string after the delimiter.
Console.WriteLine("1e) Split a string delimited by characters and " +
"return 2 non-empty elements:");
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// ------------------------------------------------------------------------------
// Split a string delimited by another string.
// ------------------------------------------------------------------------------
Console.WriteLine("2) Split a string delimited by another string:\n");
// Display the original string and delimiter string.
Console.WriteLine("2a) The original string is \"{0}\".", s2);
Console.WriteLine("The delimiter string is \"{0}\".\n", stringSeparators[0]);
// Split a string delimited by another string and return all elements.
Console.WriteLine("2b) Split a string delimited by another string and " +
"return all elements:");
result = s2.Split(stringSeparators, StringSplitOptions.None);
Show(result);
// Split the original string at the delimiter and return all non-empty elements.
Console.WriteLine("2c) Split a string delimited by another string and " +
"return all non-empty elements:");
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// Split the original string into the empty string before the
// delimiter and the remainder of the original string after the delimiter.
Console.WriteLine("2d) Split a string delimited by another string and " +
"return 2 elements:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.None);
Show(result);
// Split the original string into the string after the delimiter and the
// remainder of the original string after the delimiter.
Console.WriteLine("2e) Split a string delimited by another string and " +
"return 2 non-empty elements:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// Display the array of separated strings using a local function
void Show(string[] entries)
{
Console.WriteLine("The return value contains these {0} elements:", entries.Length);
foreach (string entry in entries)
{
Console.Write("<{0}>", entry);
}
Console.Write("\n\n");
}
/*
This example produces the following results:
1) Split a string delimited by characters:
1a )The original string is ",ONE,,TWO,,,THREE,,".
The delimiter character is ','.
1b) Split a string delimited by characters and return all elements:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>
1c) Split a string delimited by characters and return all non-empty elements:
The return value contains these 3 elements:
<ONE><TWO><THREE>
1d) Split a string delimited by characters and return 2 elements:
The return value contains these 2 elements:
<><ONE,,TWO,,,THREE,,>
1e) Split a string delimited by characters and return 2 non-empty elements:
The return value contains these 2 elements:
<ONE><TWO,,,THREE,,>
2) Split a string delimited by another string:
2a) The original string is "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".
The delimiter string is "[stop]".
2b) Split a string delimited by another string and return all elements:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>
2c) Split a string delimited by another string and return all non-empty elements:
The return value contains these 3 elements:
<ONE><TWO><THREE>
2d) Split a string delimited by another string and return 2 elements:
The return value contains these 2 elements:
<><ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]>
2e) Split a string delimited by another string and return 2 non-empty elements:
The return value contains these 2 elements:
<ONE><TWO[stop][stop][stop]THREE[stop][stop]>
*/

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

Комментарии

Сведения о возвращаемом значенииReturn value details

Строки разделителей не включаются в элементы возвращаемого массива.Delimiter strings are not included in the elements of the returned array.

Если в этом экземпляре count больше подстрок, то первый count минус 1 подстрока возвращается в первые count меньше 1 элементов возвращаемого значения, а остальные символы в этом экземпляре возвращаются в последнем возвращаемого значения.If there are more than count substrings in this instance, the first count minus 1 substrings are returned in the first count minus 1 elements of the return value, and the remaining characters in this instance are returned in the last element of the return value.

Если count больше числа подстрок, возвращаются доступные подстроки и исключение не создается.If count is greater than the number of substrings, the available substrings are returned and no exception is thrown.

Сведения о сравненииComparison details

Метод извлекает подстроки в этой строке, разделенные одной или несколькими строками separator в параметре, и возвращает эти подстроки как элементы массива. SplitThe Split method extracts the substrings in this string that are delimited by one or more of the strings in the separator parameter, and returns those substrings as elements of an array.

Чтобы избежать неоднозначных результатов separatorSplit , когда строки в имеют общие символы, метод переходит от начала до конца значения экземпляра и соответствует первому элементу в separator , который равен разделителю в вхождение.To avoid ambiguous results when strings in separator have characters in common, the Split method proceeds from the beginning to the end of the value of the instance, and matches the first element in separator that is equal to a delimiter in the instance.Порядок, в котором подстроки встречаются в экземпляре, имеет приоритет над порядком элементов в separator.The order in which substrings are encountered in the instance takes precedence over the order of elements in separator.

Однако если первый элемент 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".

При разделении строки на символ-разделитель используйте IndexOf метод или IndexOfAny для нахождение символа разделителя в строке.If you are splitting a string at a separator character, use the IndexOf or IndexOfAny method to locate a separator character in the string.При разделении строки в строке-разделителе используйте IndexOf метод или IndexOfAny для нахождение первого символа строки разделителя.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 метод, чтобы разделить его на подстроки.When a string is delimited by a known set of strings, you can use the Split method to separate it into substrings.

Сведения о возвращаемом значенииReturn value details

Строки разделителей не включаются в элементы возвращаемого массива.Delimiter strings are not included in the elements of the returned array.Например, если separator массив содержит строку "--", а значение текущего экземпляра строки — "AA--BB-CC", метод возвращает массив, содержащий три элемента: "AA", "BB" и "CC".For example, if the separator array includes the string "--" and the value of the current string instance is "aa--bb-cc", the method returns an array that contains three elements: "aa", "bb", and "cc".

Если этот экземпляр не содержит строк в separator, возвращаемый массив состоит из одного элемента, содержащего этот экземпляр.If this instance does not contain any of the strings in separator, the returned array consists of a single element that contains this instance.

Сведения о сравненииComparison details

Метод извлекает подстроки в этой строке, разделенные одной или несколькими строками separator в параметре, и возвращает эти подстроки как элементы массива. SplitThe Split method extracts the substrings in this string that are delimited by one or more of the strings in the separator parameter, and returns those substrings as elements of an array.

Чтобы избежать неоднозначных результатов 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.Порядок, в котором подстроки встречаются в экземпляре, имеет приоритет над порядком элементов в separator.The order in which substrings are encountered in the instance takes precedence over the order of elements in separator.

Однако, если первый элемент 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".

При разделении строки на символ-разделитель используйте IndexOf метод или IndexOfAny для нахождение символа разделителя в строке.If you are splitting a string at a separator character, use the IndexOf or IndexOfAny method to locate a separator character in the string.При разделении строки в строке-разделителе используйте IndexOf метод или IndexOfAny для нахождение первого символа строки разделителя.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.

// This example demonstrates the String() methods that use
// the StringSplitOptions enumeration.
string s1 = ",ONE,,TWO,,,THREE,,";
string s2 = "[stop]" +
"ONE[stop][stop]" +
"TWO[stop][stop][stop]" +
"THREE[stop][stop]";
char[] charSeparators = new char[] {','};
string[] stringSeparators = new string[] {"[stop]"};
string[] result;
// ------------------------------------------------------------------------------
// Split a string delimited by characters.
// ------------------------------------------------------------------------------
Console.WriteLine("1) Split a string delimited by characters:\n");
// Display the original string and delimiter characters.
Console.WriteLine("1a )The original string is \"{0}\".", s1);
Console.WriteLine("The delimiter character is '{0}'.\n",
charSeparators[0]);
// Split a string delimited by characters and return all elements.
Console.WriteLine("1b) Split a string delimited by characters and " +
"return all elements:");
result = s1.Split(charSeparators, StringSplitOptions.None);
Show(result);
// Split a string delimited by characters and return all non-empty elements.
Console.WriteLine("1c) Split a string delimited by characters and " +
"return all non-empty elements:");
result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// Split the original string into the string and empty string before the
// delimiter and the remainder of the original string after the delimiter.
Console.WriteLine("1d) Split a string delimited by characters and " +
"return 2 elements:");
result = s1.Split(charSeparators, 2, StringSplitOptions.None);
Show(result);
// Split the original string into the string after the delimiter and the
// remainder of the original string after the delimiter.
Console.WriteLine("1e) Split a string delimited by characters and " +
"return 2 non-empty elements:");
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// ------------------------------------------------------------------------------
// Split a string delimited by another string.
// ------------------------------------------------------------------------------
Console.WriteLine("2) Split a string delimited by another string:\n");
// Display the original string and delimiter string.
Console.WriteLine("2a) The original string is \"{0}\".", s2);
Console.WriteLine("The delimiter string is \"{0}\".\n", stringSeparators[0]);
// Split a string delimited by another string and return all elements.
Console.WriteLine("2b) Split a string delimited by another string and " +
"return all elements:");
result = s2.Split(stringSeparators, StringSplitOptions.None);
Show(result);
// Split the original string at the delimiter and return all non-empty elements.
Console.WriteLine("2c) Split a string delimited by another string and " +
"return all non-empty elements:");
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// Split the original string into the empty string before the
// delimiter and the remainder of the original string after the delimiter.
Console.WriteLine("2d) Split a string delimited by another string and " +
"return 2 elements:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.None);
Show(result);
// Split the original string into the string after the delimiter and the
// remainder of the original string after the delimiter.
Console.WriteLine("2e) Split a string delimited by another string and " +
"return 2 non-empty elements:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// Display the array of separated strings using a local function
void Show(string[] entries)
{
Console.WriteLine("The return value contains these {0} elements:", entries.Length);
foreach (string entry in entries)
{
Console.Write("<{0}>", entry);
}
Console.Write("\n\n");
}
/*
This example produces the following results:
1) Split a string delimited by characters:
1a )The original string is ",ONE,,TWO,,,THREE,,".
The delimiter character is ','.
1b) Split a string delimited by characters and return all elements:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>
1c) Split a string delimited by characters and return all non-empty elements:
The return value contains these 3 elements:
<ONE><TWO><THREE>
1d) Split a string delimited by characters and return 2 elements:
The return value contains these 2 elements:
<><ONE,,TWO,,,THREE,,>
1e) Split a string delimited by characters and return 2 non-empty elements:
The return value contains these 2 elements:
<ONE><TWO,,,THREE,,>
2) Split a string delimited by another string:
2a) The original string is "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".
The delimiter string is "[stop]".
2b) Split a string delimited by another string and return all elements:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>
2c) Split a string delimited by another string and return all non-empty elements:
The return value contains these 3 elements:
<ONE><TWO><THREE>
2d) Split a string delimited by another string and return 2 elements:
The return value contains these 2 elements:
<><ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]>
2e) Split a string delimited by another string and return 2 non-empty elements:
The return value contains these 2 elements:
<ONE><TWO[stop][stop][stop]THREE[stop][stop]>
*/

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

Комментарии

Сведения о возвращаемом значенииReturn value details

Символы-разделители (символы в separator массиве) не включаются в элементы возвращаемого массива.Delimiter characters (the characters in the separator array) are not included in the elements of the returned array.Например, если separator массив содержит символ "-", а значение текущего экземпляра строки — "AA-BB-CC", метод возвращает массив, содержащий три элемента: "AA", "BB" и "CC".For example, if the separator array includes the character "-" and the value of the current string instance is "aa-bb-cc", the method returns an array that contains three elements: "aa", "bb", and "cc".

Если этот экземпляр не содержит символов в separator, возвращаемый массив состоит из одного элемента, содержащего этот экземпляр.If this instance does not contain any of the characters in separator, the returned array consists of a single element that contains this instance.

Сведения о сравненииComparison details

Метод извлекает подстроки в этой строке, разделенные одним или несколькими символами separator в параметре, и возвращает эти подстроки как элементы массива. SplitThe Split method extracts the substrings in this string that are delimited by one or more of the characters in the separator parameter, and returns those substrings as elements of an array.

При разделении строки на символ-разделитель используйте IndexOf метод или IndexOfAny для нахождение символа разделителя в строке.If you are splitting a string at a separator character, use the IndexOf or IndexOfAny method to locate a separator character in the string.При разделении строки в строке-разделителе используйте IndexOf метод или IndexOfAny для нахождение первого символа строки разделителя.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.

Разбивает строку на максимальное число подстрок в зависимости от символов в массиве.Splits a string into a maximum number of substrings based on the characters in an array.Можно также указать максимальное число возвращаемых подстрок.You also specify the maximum number of substrings to return.

Если в этом экземпляре count больше подстрок, то первый count минус 1 подстрока возвращается в первые count меньше 1 элементов возвращаемого значения, а остальные символы в этом экземпляре возвращаются в последнем возвращаемого значения.If there are more than count substrings in this instance, the first count minus 1 substrings are returned in the first count minus 1 elements of the return value, and the remaining characters in this instance are returned in the last element of the return value.

Если count больше числа подстрок, возвращаются доступные подстроки и исключение не создается.If count is greater than the number of substrings, the available substrings are returned and no exception is thrown.

При разделении строки на символ-разделитель используйте IndexOf метод или IndexOfAny для нахождение символа разделителя в строке.If you are splitting a string at a separator character, use the IndexOf or IndexOfAny method to locate a separator character in the string.При разделении строки в строке-разделителе используйте IndexOf метод или IndexOfAny для нахождение первого символа строки разделителя.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.

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

Комментарии

Если строка отделяется от известного набора символов, можно использовать Split(Char[]) метод, чтобы разделить его на подстроки.When a string is delimited by a known set of characters, you can use the Split(Char[]) method to separate it into substrings.

Сведения о возвращаемом значенииReturn value details

Символы разделителей не включаются в элементы возвращаемого массива.Delimiter characters are not included in the elements of the returned array.Например, если массив разделителя содержит символ "-", а значение текущего экземпляра строки — "AA-BB-CC", метод возвращает массив, содержащий три элемента: "AA", "BB" и "CC".For example, if the separator array includes the character "-" and the value of the current string instance is "aa-bb-cc", the method returns an array that contains three elements: "aa", "bb", and "cc".

Если этот экземпляр не содержит символов в separator, возвращаемый массив состоит из одного элемента, содержащего этот экземпляр.If this instance does not contain any of the characters in separator, the returned array consists of a single element that contains this instance.

Хотя единственный параметр для этой перегрузки 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.

Module Example
Public Sub Main()
Dim value As String = "This is a short string."
Dim delimiter As Char = "s"c
Dim substrings() As String = value.Split(delimiter)
For Each substring In substrings
Console.WriteLine(substring)
Next
End Sub
End Module
' The example displays the following output:
' Thi
' i
' a
' hort
' tring.

Поскольку параметр снабжен ParamArrayAttribute атрибутом, компиляторы будут интерпретировать один символ как одноэлементный массив символов. separatorBecause the separator parameter is decorated with the ParamArrayAttribute attribute, compilers will interpret a single character as a single-element character array.Это не так для других String.Split перегрузок, separator включающих параметр. необходимо явно передать эти перегрузки separator в качестве аргумента массив символов.This is not the case for other String.Split overloads that include a separator parameter; you must explicitly pass these overloads a character array as the separator argument.

Сведения о сравненииComparison details

Метод извлекает подстроки в этой строке, разделенные одним или несколькими символами separator в массиве, и возвращает эти подстроки как элементы массива. Split(Char[])The Split(Char[]) method extracts the substrings in this string that are delimited by one or more of the characters in the separator array, and returns those substrings as elements of an array.