String.Split Metoda
Definice
Důležité
Některé informace platí pro předběžně vydaný produkt, který se může zásadně změnit, než ho výrobce nebo autor vydá. Microsoft neposkytuje žádné záruky, výslovné ani předpokládané, týkající se zde uváděných informací.
Vrátí pole řetězců obsahující podřetězce v této instanci, které jsou odděleny prvky zadaného řetězce nebo pole znaků Unicode.
Přetížení
| Name | Description |
|---|---|
| Split(Rune, StringSplitOptions) | |
| Split(String[], Int32, StringSplitOptions) |
Rozdělí řetězec na maximální počet podřetězců na základě zadaných oddělovacích řetězců a volitelně možností. |
| Split(Rune, Int32, StringSplitOptions) | |
| Split(Char[], Int32, StringSplitOptions) |
Rozdělí řetězec na maximální počet podřetězců na základě zadaných znaků s oddělovači a volitelně možností. |
| Split(Char, Int32, StringSplitOptions) |
Rozdělí řetězec na maximální počet podřetězců na základě zadaného oddělovače znaků, volitelně vynechá prázdné podřetězce z výsledku. |
| Split(String[], StringSplitOptions) |
Rozdělí řetězec na podřetězce na základě zadaného řetězce s oddělovači a volitelně i možností. |
| Split(String, Int32, StringSplitOptions) |
Rozdělí řetězec na maximální počet podřetězců na základě zadaného oddělovacího řetězce a volitelně možností. |
| Split(Char[], StringSplitOptions) |
Rozdělí řetězec na podřetězce na základě zadaných znaků a možností s oddělovači. |
| Split(Char[], Int32) |
Rozdělí řetězec na maximální počet podřetězců na základě zadaných znaků s oddělovači. |
| Split(Char, StringSplitOptions) |
Rozdělí řetězec na podřetězce na základě zadaného znaku oddělovače a volitelně i možností. |
| Split(ReadOnlySpan<Char>) |
Rozdělí řetězec na podřetězce na základě zadaných znaků s oddělovači. |
| Split(Char[]) |
Rozdělí řetězec na podřetězce na základě zadaných znaků s oddělovači. |
| Split(String, StringSplitOptions) |
Rozdělí řetězec na podřetězce založené na zadaném oddělovači řetězců. |
Poznámky
Split slouží k rozdělení řetězce s oddělovači na podřetězce. K určení nuly nebo více oddělovacích znaků nebo řetězců můžete použít pole znaků nebo pole řetězců. Pokud nejsou zadány žádné oddělovače, řetězec se rozdělí na prázdné znaky.
Split Přetížení metody umožňují omezit počet podřetězců vrácených metodou (Split(Char[], Int32)metodou), určit, zda zahrnout prázdné řetězce a/nebo trim podřetězce ve výsledku (Split(Char[], StringSplitOptions)a Split(String[], StringSplitOptions) metody), nebo provést obojí (Split(Char[], Int32, StringSplitOptions)i Split(String[], Int32, StringSplitOptions) metody).
Spropitné
Metoda Split není vždy nejlepším způsobem, jak rozdělit řetězec s oddělovači na podřetězce. Pokud nechcete extrahovat všechny podřetězce řetězce s oddělovači nebo pokud chcete analyzovat řetězec na základě vzoru namísto sady znaků oddělovače, zvažte použití regulárních výrazů nebo zkombinujte jednu z metod hledání, která vrací index znaku s metodou Substring . Další informace naleznete v tématu Extrakce podřetězců z řetězce.
Příklad
Následující příklady ukazují tři různé přetížení String.Split(). První příklad volá Split(Char[]) přetížení a předává v jednom oddělovači.
string s = "You win some. You lose some.";
string[] subs = s.Split(' ');
foreach (var sub in subs)
{
Console.WriteLine($"Substring: {sub}");
}
// This example produces the following output:
//
// Substring: You
// Substring: win
// Substring: some.
// Substring: You
// Substring: lose
// Substring: some.
let s = "You win some. You lose some."
let subs = s.Split ' '
for sub in subs do
printfn $"Substring: {sub}"
// This example produces the following output:
//
// Substring: You
// Substring: win
// Substring: some.
// Substring: You
// Substring: lose
// Substring: some.
Dim s As String = "You win some. You lose some."
Dim subs As String() = s.Split()
For Each substring As String In subs
Console.WriteLine($"Substring: {substring}")
Next
' This example produces the following output:
'
' Substring: You
' Substring: win
' Substring: some.
' Substring: You
' Substring: lose
' Substring: some.
Jak vidíte, znaky tečky (.) jsou zahrnuty do dvou podřetěžců. Pokud chcete znaky tečky vyloučit, můžete ho přidat jako další znak oddělovače. Další příklad ukazuje, jak to udělat.
string s = "You win some. You lose some.";
string[] subs = s.Split(' ', '.');
foreach (var sub in subs)
{
Console.WriteLine($"Substring: {sub}");
}
// This example produces the following output:
//
// Substring: You
// Substring: win
// Substring: some
// Substring:
// Substring: You
// Substring: lose
// Substring: some
// Substring:
let s = "You win some. You lose some."
let subs = s.Split(' ', '.')
for sub in subs do
printfn $"Substring: {sub}"
// This example produces the following output:
//
// Substring: You
// Substring: win
// Substring: some
// Substring:
// Substring: You
// Substring: lose
// Substring: some
// Substring:
Dim s As String = "You win some. You lose some."
Dim subs As String() = s.Split(" "c, "."c)
For Each substring As String In subs
Console.WriteLine($"Substring: {substring}")
Next
' This example produces the following output:
'
' Substring: You
' Substring: win
' Substring: some
' Substring:
' Substring: You
' Substring: lose
' Substring: some
' Substring:
Tečky jsou pryč z podřetěžců, ale nyní byly zahrnuty dva nadbytečné prázdné podřetětěce. Tyto prázdné podřetětěce představují podřetězí mezi slovem a tečkou, která následuje za ním. Chcete-li vynechat prázdné podřetězce z výsledného pole, můžete volat přetížení Split(Char[], StringSplitOptions) a určit pro parametr StringSplitOptions.RemoveEmptyEntries hodnotu options.
string s = "You win some. You lose some.";
char[] separators = new char[] { ' ', '.' };
string[] subs = s.Split(separators, StringSplitOptions.RemoveEmptyEntries);
foreach (var sub in subs)
{
Console.WriteLine($"Substring: {sub}");
}
// This example produces the following output:
//
// Substring: You
// Substring: win
// Substring: some
// Substring: You
// Substring: lose
// Substring: some
let s = "You win some. You lose some."
let separators = [| ' '; '.' |]
let subs = s.Split(separators, StringSplitOptions.RemoveEmptyEntries)
for sub in subs do
printfn $"Substring: {sub}"
// This example produces the following output:
//
// Substring: You
// Substring: win
// Substring: some
// Substring: You
// Substring: lose
// Substring: some
Dim s As String = "You win some. You lose some."
Dim separators As Char() = New Char() {" "c, "."c}
Dim subs As String() = s.Split(separators, StringSplitOptions.RemoveEmptyEntries)
For Each substring As String In subs
Console.WriteLine($"Substring: {substring}")
Next
' This example produces the following output:
'
' Substring: You
' Substring: win
' Substring: some
' Substring: You
' Substring: lose
' Substring: some
Oddíly pro jednotlivá přetížení String.Split() obsahují další příklady.
Split(Rune, StringSplitOptions)
public string[] Split(System.Text.Rune separator, StringSplitOptions options = System.StringSplitOptions.None);
member this.Split : System.Text.Rune * StringSplitOptions -> string[]
Public Function Split (separator As Rune, Optional options As StringSplitOptions = System.StringSplitOptions.None) As String()
Parametry
- separator
- Rune
- options
- StringSplitOptions
Návraty
Platí pro
Split(String[], Int32, StringSplitOptions)
- Zdroj:
- String.Manipulation.cs
- Zdroj:
- String.Manipulation.cs
- Zdroj:
- String.Manipulation.cs
- Zdroj:
- String.Manipulation.cs
Rozdělí řetězec na maximální počet podřetězců na základě zadaných oddělovacích řetězců a volitelně možností.
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()
Parametry
- separator
- String[]
Řetězce, které odděluje podřetězce v tomto řetězci, prázdné pole, které neobsahuje žádné oddělovače, nebo null.
- count
- Int32
Maximální počet podřetěžců, které se mají vrátit.
- options
- StringSplitOptions
Bitové kombinace hodnot výčtu, která určuje, zda se mají oříznout podřetězce a zahrnout prázdné podřetězce.
Návraty
Matice, jejíž prvky obsahují podřetězce v tomto řetězci, které jsou odděleny jedním nebo více řetězci v separator. Další informace najdete v části Poznámky.
- Atributy
Výjimky
count je negativní.
options není jednou z StringSplitOptions hodnot.
Příklady
Následující příklad používá StringSplitOptions výčet k zahrnutí nebo vyloučení podřetězdců vygenerovaných metodou Split .
// This example demonstrates the String.Split() methods that use
// the StringSplitOptions enumeration.
// Example 1: Split a string delimited by characters
Console.WriteLine("1) Split a string delimited by characters:\n");
string s1 = ",ONE,, TWO,, , THREE,,";
char[] charSeparators = new char[] { ',' };
string[] result;
Console.WriteLine($"The original string is: \"{s1}\".");
Console.WriteLine($"The delimiter character is: '{charSeparators[0]}'.\n");
// Split the string and return all elements
Console.WriteLine("1a) Return all elements:");
result = s1.Split(charSeparators, StringSplitOptions.None);
Show(result);
// Split the string and return all elements with whitespace trimmed
Console.WriteLine("1b) Return all elements with whitespace trimmed:");
result = s1.Split(charSeparators, StringSplitOptions.TrimEntries);
Show(result);
// Split the string and return all non-empty elements
Console.WriteLine("1c) Return all non-empty elements:");
result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// Split the string and return all non-whitespace elements with whitespace trimmed
Console.WriteLine("1d) Return all non-whitespace elements with whitespace trimmed:");
result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
Show(result);
// Split the string into only two elements, keeping the remainder in the last match
Console.WriteLine("1e) Split into only two elements:");
result = s1.Split(charSeparators, 2, StringSplitOptions.None);
Show(result);
// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("1f) Split into only two elements with whitespace trimmed:");
result = s1.Split(charSeparators, 2, StringSplitOptions.TrimEntries);
Show(result);
// Split the string into only two non-empty elements, keeping the remainder in the last match
Console.WriteLine("1g) Split into only two non-empty elements:");
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("1h) Split into only two non-whitespace elements with whitespace trimmed:");
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
Show(result);
// Example 2: Split a string delimited by another string
Console.WriteLine("2) Split a string delimited by another string:\n");
string s2 = "[stop]" +
"ONE[stop] [stop]" +
"TWO [stop][stop] [stop]" +
"THREE[stop][stop] ";
string[] stringSeparators = new string[] { "[stop]" };
Console.WriteLine($"The original string is: \"{s2}\".");
Console.WriteLine($"The delimiter string is: \"{stringSeparators[0]}\".\n");
// Split the string and return all elements
Console.WriteLine("2a) Return all elements:");
result = s2.Split(stringSeparators, StringSplitOptions.None);
Show(result);
// Split the string and return all elements with whitespace trimmed
Console.WriteLine("2b) Return all elements with whitespace trimmed:");
result = s2.Split(stringSeparators, StringSplitOptions.TrimEntries);
Show(result);
// Split the string and return all non-empty elements
Console.WriteLine("2c) Return all non-empty elements:");
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// Split the string and return all non-whitespace elements with whitespace trimmed
Console.WriteLine("2d) Return all non-whitespace elements with whitespace trimmed:");
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
Show(result);
// Split the string into only two elements, keeping the remainder in the last match
Console.WriteLine("2e) Split into only two elements:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.None);
Show(result);
// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("2f) Split into only two elements with whitespace trimmed:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.TrimEntries);
Show(result);
// Split the string into only two non-empty elements, keeping the remainder in the last match
Console.WriteLine("2g) Split into only two non-empty elements:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("2h) Split into only two non-whitespace elements with whitespace trimmed:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
Show(result);
// Display the array of separated strings using a local function
void Show(string[] entries)
{
Console.WriteLine($"The return value contains these {entries.Length} elements:");
foreach (string entry in entries)
{
Console.Write($"<{entry}>");
}
Console.Write("\n\n");
}
/*
This example produces the following results:
1) Split a string delimited by characters:
The original string is: ",ONE,, TWO,, , THREE,,".
The delimiter character is: ','.
1a) Return all elements:
The return value contains these 9 elements:
<><ONE><>< TWO><>< >< THREE><><>
1b) Return all elements with whitespace trimmed:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>
1c) Return all non-empty elements:
The return value contains these 4 elements:
<ONE>< TWO>< >< THREE>
1d) Return all non-whitespace elements with whitespace trimmed:
The return value contains these 3 elements:
<ONE><TWO><THREE>
1e) Split into only two elements:
The return value contains these 2 elements:
<><ONE,, TWO,, , THREE,,>
1f) Split into only two elements with whitespace trimmed:
The return value contains these 2 elements:
<><ONE,, TWO,, , THREE,,>
1g) Split into only two non-empty elements:
The return value contains these 2 elements:
<ONE>< TWO,, , THREE,,>
1h) Split into only two non-whitespace elements with whitespace trimmed:
The return value contains these 2 elements:
<ONE><TWO,, , THREE,,>
2) Split a string delimited by another string:
The original string is: "[stop]ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] ".
The delimiter string is: "[stop]".
2a) Return all elements:
The return value contains these 9 elements:
<><ONE>< ><TWO ><>< ><THREE><>< >
2b) Return all elements with whitespace trimmed:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>
2c) Return all non-empty elements:
The return value contains these 6 elements:
<ONE>< ><TWO >< ><THREE>< >
2d) Return all non-whitespace elements with whitespace trimmed:
The return value contains these 3 elements:
<ONE><TWO><THREE>
2e) Split into only two elements:
The return value contains these 2 elements:
<><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] >
2f) Split into only two elements with whitespace trimmed:
The return value contains these 2 elements:
<><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop]>
2g) Split into only two non-empty elements:
The return value contains these 2 elements:
<ONE>< [stop]TWO [stop][stop] [stop]THREE[stop][stop] >
2h) Split into only two non-whitespace elements with whitespace trimmed:
The return value contains these 2 elements:
<ONE><TWO [stop][stop] [stop]THREE[stop][stop]>
*/
// This example demonstrates the String.Split() methods that use
// the StringSplitOptions enumeration.
// Display the array of separated strings using a local function
let show (entries: string[]) =
printfn $"The return value contains these {entries.Length} elements:"
for entry in entries do
printf $"<{entry}>"
printf "\n\n"
// Example 1: Split a string delimited by characters
printfn "1) Split a string delimited by characters:\n"
let s1 = ",ONE,, TWO,, , THREE,,"
let charSeparators = [| ',' |]
printfn $"The original string is: \"{s1}\"."
printfn $"The delimiter character is: '{charSeparators[0]}'.\n"
// Split the string and return all elements
printfn "1a) Return all elements:"
let result = s1.Split(charSeparators, StringSplitOptions.None)
show result
// Split the string and return all elements with whitespace trimmed
printfn "1b) Return all elements with whitespace trimmed:"
let result = s1.Split(charSeparators, StringSplitOptions.TrimEntries)
show result
// Split the string and return all non-empty elements
printfn "1c) Return all non-empty elements:"
let result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries)
show result
// Split the string and return all non-whitespace elements with whitespace trimmed
printfn "1d) Return all non-whitespace elements with whitespace trimmed:"
let result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)
show result
// Split the string into only two elements, keeping the remainder in the last match
printfn "1e) Split into only two elements:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.None)
show result
// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
printfn "1f) Split into only two elements with whitespace trimmed:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.TrimEntries)
show result
// Split the string into only two non-empty elements, keeping the remainder in the last match
printfn "1g) Split into only two non-empty elements:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
show result
// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
printfn "1h) Split into only two non-whitespace elements with whitespace trimmed:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)
show result
// Example 2: Split a string delimited by another string
printfn "2) Split a string delimited by another string:\n"
let s2 = "[stop]" +
"ONE[stop] [stop]" +
"TWO [stop][stop] [stop]" +
"THREE[stop][stop] "
let stringSeparators = [| "[stop]" |]
printfn $"The original string is: \"{s2}\"."
printfn $"The delimiter string is: \"{stringSeparators[0]}\".\n"
// Split the string and return all elements
printfn "2a) Return all elements:"
let result = s2.Split(stringSeparators, StringSplitOptions.None)
show result
// Split the string and return all elements with whitespace trimmed
printfn "2b) Return all elements with whitespace trimmed:"
let result = s2.Split(stringSeparators, StringSplitOptions.TrimEntries)
show result
// Split the string and return all non-empty elements
printfn "2c) Return all non-empty elements:"
let result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)
show result
// Split the string and return all non-whitespace elements with whitespace trimmed
printfn "2d) Return all non-whitespace elements with whitespace trimmed:"
let result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)
show result
// Split the string into only two elements, keeping the remainder in the last match
printfn "2e) Split into only two elements:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.None)
show result
// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
printfn "2f) Split into only two elements with whitespace trimmed:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.TrimEntries)
show result
// Split the string into only two non-empty elements, keeping the remainder in the last match
printfn "2g) Split into only two non-empty elements:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
show result
// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
printfn "2h) Split into only two non-whitespace elements with whitespace trimmed:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)
show result
(*
This example produces the following results:
1) Split a string delimited by characters:
The original string is: ",ONE,, TWO,, , THREE,,".
The delimiter character is: ','.
1a) Return all elements:
The return value contains these 9 elements:
<><ONE><>< TWO><>< >< THREE><><>
1b) Return all elements with whitespace trimmed:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>
1c) Return all non-empty elements:
The return value contains these 4 elements:
<ONE>< TWO>< >< THREE>
1d) Return all non-whitespace elements with whitespace trimmed:
The return value contains these 3 elements:
<ONE><TWO><THREE>
1e) Split into only two elements:
The return value contains these 2 elements:
<><ONE,, TWO,, , THREE,,>
1f) Split into only two elements with whitespace trimmed:
The return value contains these 2 elements:
<><ONE,, TWO,, , THREE,,>
1g) Split into only two non-empty elements:
The return value contains these 2 elements:
<ONE>< TWO,, , THREE,,>
1h) Split into only two non-whitespace elements with whitespace trimmed:
The return value contains these 2 elements:
<ONE><TWO,, , THREE,,>
2) Split a string delimited by another string:
The original string is: "[stop]ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] ".
The delimiter string is: "[stop]".
2a) Return all elements:
The return value contains these 9 elements:
<><ONE>< ><TWO ><>< ><THREE><>< >
2b) Return all elements with whitespace trimmed:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>
2c) Return all non-empty elements:
The return value contains these 6 elements:
<ONE>< ><TWO >< ><THREE>< >
2d) Return all non-whitespace elements with whitespace trimmed:
The return value contains these 3 elements:
<ONE><TWO><THREE>
2e) Split into only two elements:
The return value contains these 2 elements:
<><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] >
2f) Split into only two elements with whitespace trimmed:
The return value contains these 2 elements:
<><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop]>
2g) Split into only two non-empty elements:
The return value contains these 2 elements:
<ONE>< [stop]TWO [stop][stop] [stop]THREE[stop][stop] >
2h) Split into only two non-whitespace elements with whitespace trimmed:
The return value contains these 2 elements:
<ONE><TWO [stop][stop] [stop]THREE[stop][stop]>
*)
Public Shared Sub StringSplitOptionsExamples()
' This example demonstrates the String.Split() methods that use
' the StringSplitOptions enumeration.
' Example 1: Split a string delimited by characters
Console.WriteLine("1) Split a string delimited by characters:" & vbCrLf)
Dim s1 As String = ",ONE,, TWO,, , THREE,,"
Dim charSeparators() As Char = {","c}
Dim result() As String
Console.WriteLine("The original string is: ""{0}"".", s1)
Console.WriteLine("The delimiter character is: '{0}'." & vbCrLf, charSeparators(0))
' Split the string and return all elements
Console.WriteLine("1a) Return all elements:")
result = s1.Split(charSeparators, StringSplitOptions.None)
Show(result)
' Split the string and return all elements with whitespace trimmed
Console.WriteLine("1b) Return all elements with whitespace trimmed:")
result = s1.Split(charSeparators, StringSplitOptions.TrimEntries)
Show(result)
' Split the string and return all non-empty elements
Console.WriteLine("1c) Return all non-empty elements:")
result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries)
Show(result)
' Split the string and return all non-whitespace elements with whitespace trimmed
Console.WriteLine("1d) Return all non-whitespace elements with whitespace trimmed:")
result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries)
Show(result)
' Split the string into only two elements, keeping the remainder in the last match
Console.WriteLine("1e) Split into only two elements:")
result = s1.Split(charSeparators, 2, StringSplitOptions.None)
Show(result)
' Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("1f) Split into only two elements with whitespace trimmed:")
result = s1.Split(charSeparators, 2, StringSplitOptions.TrimEntries)
Show(result)
' Split the string into only two non-empty elements, keeping the remainder in the last match
Console.WriteLine("1g) Split into only two non-empty elements:")
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
Show(result)
' Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("1h) Split into only two non-whitespace elements with whitespace trimmed:")
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries)
Show(result)
' Example 2: Split a string delimited by another string
Console.WriteLine("2) Split a string delimited by another string:" & vbCrLf)
Dim s2 As String = "[stop]" +
"ONE[stop] [stop]" +
"TWO [stop][stop] [stop]" +
"THREE[stop][stop] "
Dim stringSeparators() As String = {"[stop]"}
Console.WriteLine("The original string is: ""{0}"".", s2)
Console.WriteLine("The delimiter string is: ""{0}""." & vbCrLf, stringSeparators(0))
' Split the string and return all elements
Console.WriteLine("2a) Return all elements:")
result = s2.Split(stringSeparators, StringSplitOptions.None)
Show(result)
' Split the string and return all elements with whitespace trimmed
Console.WriteLine("2b) Return all elements with whitespace trimmed:")
result = s2.Split(stringSeparators, StringSplitOptions.TrimEntries)
Show(result)
' Split the string and return all non-empty elements
Console.WriteLine("2c) Return all non-empty elements:")
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)
Show(result)
' Split the string and return all non-whitespace elements with whitespace trimmed
Console.WriteLine("2d) Return all non-whitespace elements with whitespace trimmed:")
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries)
Show(result)
' Split the string into only two elements, keeping the remainder in the last match
Console.WriteLine("2e) Split into only two elements:")
result = s2.Split(stringSeparators, 2, StringSplitOptions.None)
Show(result)
' Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("2f) Split into only two elements with whitespace trimmed:")
result = s2.Split(stringSeparators, 2, StringSplitOptions.TrimEntries)
Show(result)
' Split the string into only two non-empty elements, keeping the remainder in the last match
Console.WriteLine("2g) Split into only two non-empty elements:")
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
Show(result)
' Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("2h) Split into only two non-whitespace elements with whitespace trimmed:")
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries)
Show(result)
End Sub
' Display the array of separated strings.
Public Shared Sub Show(ByVal entries() As String)
Console.WriteLine("The return value contains these {0} elements:", entries.Length)
Dim entry As String
For Each entry In entries
Console.Write("<{0}>", entry)
Next entry
Console.Write(vbCrLf & vbCrLf)
End Sub
'This example produces the following results:
'
' 1) Split a string delimited by characters:
'
' The original string is: ",ONE,, TWO,, , THREE,,".
' The delimiter character is: ','.
'
' 1a) Return all elements:
' The return value contains these 9 elements:
' <><ONE><>< TWO><>< >< THREE><><>
'
' 1b) Return all elements with whitespace trimmed:
' The return value contains these 9 elements:
' <><ONE><><TWO><><><THREE><><>
'
' 1c) Return all non-empty elements:
' The return value contains these 4 elements:
' <ONE>< TWO>< >< THREE>
'
' 1d) Return all non-whitespace elements with whitespace trimmed:
' The return value contains these 3 elements:
' <ONE><TWO><THREE>
'
' 1e) Split into only two elements:
' The return value contains these 2 elements:
' <><ONE,, TWO,, , THREE,,>
'
' 1f) Split into only two elements with whitespace trimmed:
' The return value contains these 2 elements:
' <><ONE,, TWO,, , THREE,,>
'
' 1g) Split into only two non-empty elements:
' The return value contains these 2 elements:
' <ONE>< TWO,, , THREE,,>
'
' 1h) Split into only two non-whitespace elements with whitespace trimmed:
' The return value contains these 2 elements:
' <ONE><TWO,, , THREE,,>
'
' 2) Split a string delimited by another string:
'
' The original string is: "[stop]ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] ".
' The delimiter string is: "[stop]".
'
' 2a) Return all elements:
' The return value contains these 9 elements:
' <><ONE>< ><TWO ><>< ><THREE><>< >
'
' 2b) Return all elements with whitespace trimmed:
' The return value contains these 9 elements:
' <><ONE><><TWO><><><THREE><><>
'
' 2c) Return all non-empty elements:
' The return value contains these 6 elements:
' <ONE>< ><TWO >< ><THREE>< >
'
' 2d) Return all non-whitespace elements with whitespace trimmed:
' The return value contains these 3 elements:
' <ONE><TWO><THREE>
'
' 2e) Split into only two elements:
' The return value contains these 2 elements:
' <><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] >
'
' 2f) Split into only two elements with whitespace trimmed:
' The return value contains these 2 elements:
' <><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop]>
'
' 2g) Split into only two non-empty elements:
' The return value contains these 2 elements:
' <ONE>< [stop]TWO [stop][stop] [stop]THREE[stop][stop] >
'
' 2h) Split into only two non-whitespace elements with whitespace trimmed:
' The return value contains these 2 elements:
' <ONE><TWO [stop][stop] [stop]THREE[stop][stop]>
'
Poznámky
Řetězce oddělovače nejsou zahrnuty do prvků vráceného pole.
Pokud tato instance neobsahuje žádný z řetězců v separatornebo count parametr je 1, vrácená matice se skládá z jednoho prvku, který obsahuje tuto instanci.
separator Pokud je null parametr nebo neobsahuje žádné znaky, předpokládá se, že prázdné znaky jsou oddělovači. Prázdné znaky jsou definovány standardem Unicode a Char.IsWhiteSpace metoda vrátí true , pokud jsou předány do něj.
Chcete-li předat null parametr string[] separator , je nutné určit typ null , který má zrušit nejednoznačnost volání z některých jiných přetížení, například Split(Char[], Int32, StringSplitOptions). Následující příklad ukazuje několik způsobů, jak jednoznačně identifikovat toto přetížení.
string phrase = "The quick brown fox";
_ = phrase.Split(default(string[]), 3, StringSplitOptions.RemoveEmptyEntries);
_ = phrase.Split((string[]?)null, 3, StringSplitOptions.RemoveEmptyEntries);
_ = phrase.Split(null as string[], 3, StringSplitOptions.RemoveEmptyEntries);
let phrase = "The quick brown fox"
phrase.Split(Unchecked.defaultof<string[]>, 3, StringSplitOptions.RemoveEmptyEntries) |> ignore
phrase.Split(null :> string[], 3, StringSplitOptions.RemoveEmptyEntries) |> ignore
phrase.Split((null: string[]), 3, StringSplitOptions.RemoveEmptyEntries) |> ignore
Dim phrase As String = "The quick brown fox"
Dim words() As String
words = phrase.Split(TryCast(Nothing, String()), 3,
StringSplitOptions.RemoveEmptyEntries)
words = phrase.Split(New String() {}, 3,
StringSplitOptions.RemoveEmptyEntries)
count Pokud je parametr nula nebo options je RemoveEmptyEntries parametr a délka této instance je nula, vrátí se prázdné pole.
Každý prvek separator definuje samostatný oddělovač, který se skládá z jednoho nebo více znaků.
options Pokud je Noneparametr a dva oddělovače jsou sousední nebo oddělovač je nalezen na začátku nebo na konci této instance, odpovídající prvek pole obsahuje Empty.
Pokud je v této instanci více než count podřetěžců, vrátí se první podřetěžce minus 1 v prvních countcount mínus 1 prvcích návratové hodnoty a zbývající znaky v této instanci se vrátí v posledním prvku návratové hodnoty.
Pokud count je větší než počet podřetětců, vrátí se dostupné podřetětězení a nevyvolá se žádná výjimka.
Pole oddělovače
Pokud se některý z prvků separator skládá z více znaků, považuje se celý podřetězen za oddělovač. Pokud je například jeden z prvků " separator 10", pokusí se rozdělit řetězec "This10is10a10string". Vrátí toto pole se čtyřmi prvky: { "This", "is", "a", "string". }.
Podrobnosti porovnání
Metoda Split extrahuje podřetězce v tomto řetězci, které jsou oddělené jedním nebo více řetězci v parametru separator , a vrátí tyto podřetězce jako prvky pole.
Metoda Split hledá oddělovače provedením porovnání pomocí pravidel řazení s rozlišováním malých a velkých písmen. Další informace o slovech, řetězcích a řadových řazeních najdete ve výčtu System.Globalization.CompareOptions .
Metoda Split ignoruje jakýkoli prvek, jehož separator hodnota je null nebo prázdný řetězec ("").
Aby nedocházelo k nejednoznačným výsledkům, pokud řetězce mají separator společné znaky, Split metoda pokračuje od začátku do konce hodnoty instance a odpovídá prvnímu prvku separator , který se rovná oddělovači v instanci. Pořadí, ve kterém jsou v instanci zjištěny podřetěděce, má přednost před pořadím prvků v separator.
Představte si například instanci, jejíž hodnota je abcdef. Pokud byl první prvek v separator "ef" a druhý prvek byl "bcde", výsledek operace rozdělení by byl "a" a "f". Důvodem je to, že podřetězi v instanci "bcde", je zjištěn a odpovídá prvku před separator výskytem podřetětězi "f".
Pokud je však první prvek separator "bcd" a druhý prvek byl "bc", výsledkem operace rozdělení bude "a" a "ef". Důvodem je to, že "bcd" je první oddělovač, separator který odpovídá oddělovači v instanci. Pokud bylo pořadí oddělovačů obrácené tak, aby první prvek byl "bc" a druhý prvek byl "bcd", výsledek by byl "a" a "def".
Důležité informace o výkonu
Metody Split přidělují paměť pro vrácený maticový objekt a String objekt pro každý prvek pole. Pokud vaše aplikace vyžaduje optimální výkon nebo pokud je správa přidělení paměti ve vaší aplikaci důležitá, zvažte použití IndexOf metody nebo IndexOfAny metody a volitelně Compare vyhledejte podřetězce v řetězci.
Pokud rozdělujete řetězec na znak oddělovače, pomocí IndexOf nebo IndexOfAny metody vyhledejte v řetězci znak oddělovače. Pokud rozdělujete řetězec na řetězec oddělovače, použijte IndexOf metodu nebo IndexOfAny vyhledejte první znak řetězce oddělovače. Pak pomocí Compare metody určete, zda se znaky za tímto prvním znakem rovnají zbývajícím znakům řetězce oddělovače.
Kromě toho platí, že pokud se ke rozdělení řetězců ve více Split voláních metod používá stejná sada znaků, zvažte vytvoření jednoho pole a odkazování na ni v každém volání metody. Tím se výrazně sníží režijní náklady na každé volání metody.
Poznámky pro volající
V rozhraní .NET Framework 3.5 a starších verzích, pokud Split(Char[]) je metoda předána separator nebo null neobsahuje žádné znaky, metoda používá mírně odlišnou sadu prázdných znaků k rozdělení řetězce, než Trim(Char[]) metoda provádí oříznutí řetězce. Počínaje rozhraním .NET Framework 4 používají obě metody stejnou sadu prázdných znaků Unicode.
Platí pro
Split(Rune, Int32, StringSplitOptions)
public string[] Split(System.Text.Rune separator, int count, StringSplitOptions options = System.StringSplitOptions.None);
member this.Split : System.Text.Rune * int * StringSplitOptions -> string[]
Public Function Split (separator As Rune, count As Integer, Optional options As StringSplitOptions = System.StringSplitOptions.None) As String()
Parametry
- separator
- Rune
- count
- Int32
- options
- StringSplitOptions
Návraty
Platí pro
Split(Char[], Int32, StringSplitOptions)
- Zdroj:
- String.Manipulation.cs
- Zdroj:
- String.Manipulation.cs
- Zdroj:
- String.Manipulation.cs
- Zdroj:
- String.Manipulation.cs
Rozdělí řetězec na maximální počet podřetězců na základě zadaných znaků s oddělovači a volitelně možností.
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()
Parametry
- separator
- Char[]
Pole znaků, které odděluje podřetězce v tomto řetězci, prázdné pole, které neobsahuje žádné oddělovače nebo null.
- count
- Int32
Maximální počet podřetěžců, které se mají vrátit.
- options
- StringSplitOptions
Bitové kombinace hodnot výčtu, která určuje, zda se mají oříznout podřetězce a zahrnout prázdné podřetězce.
Návraty
Pole, které obsahuje podřetězce v tomto řetězci, které jsou odděleny jedním nebo více znaky v separator. Další informace najdete v části Poznámky.
- Atributy
Výjimky
count je negativní.
options není jednou z StringSplitOptions hodnot.
Příklady
Následující příklad používá StringSplitOptions výčet k zahrnutí nebo vyloučení podřetězdců vygenerovaných metodou Split .
// This example demonstrates the String.Split() methods that use
// the StringSplitOptions enumeration.
// Example 1: Split a string delimited by characters
Console.WriteLine("1) Split a string delimited by characters:\n");
string s1 = ",ONE,, TWO,, , THREE,,";
char[] charSeparators = new char[] { ',' };
string[] result;
Console.WriteLine($"The original string is: \"{s1}\".");
Console.WriteLine($"The delimiter character is: '{charSeparators[0]}'.\n");
// Split the string and return all elements
Console.WriteLine("1a) Return all elements:");
result = s1.Split(charSeparators, StringSplitOptions.None);
Show(result);
// Split the string and return all elements with whitespace trimmed
Console.WriteLine("1b) Return all elements with whitespace trimmed:");
result = s1.Split(charSeparators, StringSplitOptions.TrimEntries);
Show(result);
// Split the string and return all non-empty elements
Console.WriteLine("1c) Return all non-empty elements:");
result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// Split the string and return all non-whitespace elements with whitespace trimmed
Console.WriteLine("1d) Return all non-whitespace elements with whitespace trimmed:");
result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
Show(result);
// Split the string into only two elements, keeping the remainder in the last match
Console.WriteLine("1e) Split into only two elements:");
result = s1.Split(charSeparators, 2, StringSplitOptions.None);
Show(result);
// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("1f) Split into only two elements with whitespace trimmed:");
result = s1.Split(charSeparators, 2, StringSplitOptions.TrimEntries);
Show(result);
// Split the string into only two non-empty elements, keeping the remainder in the last match
Console.WriteLine("1g) Split into only two non-empty elements:");
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("1h) Split into only two non-whitespace elements with whitespace trimmed:");
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
Show(result);
// Example 2: Split a string delimited by another string
Console.WriteLine("2) Split a string delimited by another string:\n");
string s2 = "[stop]" +
"ONE[stop] [stop]" +
"TWO [stop][stop] [stop]" +
"THREE[stop][stop] ";
string[] stringSeparators = new string[] { "[stop]" };
Console.WriteLine($"The original string is: \"{s2}\".");
Console.WriteLine($"The delimiter string is: \"{stringSeparators[0]}\".\n");
// Split the string and return all elements
Console.WriteLine("2a) Return all elements:");
result = s2.Split(stringSeparators, StringSplitOptions.None);
Show(result);
// Split the string and return all elements with whitespace trimmed
Console.WriteLine("2b) Return all elements with whitespace trimmed:");
result = s2.Split(stringSeparators, StringSplitOptions.TrimEntries);
Show(result);
// Split the string and return all non-empty elements
Console.WriteLine("2c) Return all non-empty elements:");
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// Split the string and return all non-whitespace elements with whitespace trimmed
Console.WriteLine("2d) Return all non-whitespace elements with whitespace trimmed:");
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
Show(result);
// Split the string into only two elements, keeping the remainder in the last match
Console.WriteLine("2e) Split into only two elements:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.None);
Show(result);
// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("2f) Split into only two elements with whitespace trimmed:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.TrimEntries);
Show(result);
// Split the string into only two non-empty elements, keeping the remainder in the last match
Console.WriteLine("2g) Split into only two non-empty elements:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("2h) Split into only two non-whitespace elements with whitespace trimmed:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
Show(result);
// Display the array of separated strings using a local function
void Show(string[] entries)
{
Console.WriteLine($"The return value contains these {entries.Length} elements:");
foreach (string entry in entries)
{
Console.Write($"<{entry}>");
}
Console.Write("\n\n");
}
/*
This example produces the following results:
1) Split a string delimited by characters:
The original string is: ",ONE,, TWO,, , THREE,,".
The delimiter character is: ','.
1a) Return all elements:
The return value contains these 9 elements:
<><ONE><>< TWO><>< >< THREE><><>
1b) Return all elements with whitespace trimmed:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>
1c) Return all non-empty elements:
The return value contains these 4 elements:
<ONE>< TWO>< >< THREE>
1d) Return all non-whitespace elements with whitespace trimmed:
The return value contains these 3 elements:
<ONE><TWO><THREE>
1e) Split into only two elements:
The return value contains these 2 elements:
<><ONE,, TWO,, , THREE,,>
1f) Split into only two elements with whitespace trimmed:
The return value contains these 2 elements:
<><ONE,, TWO,, , THREE,,>
1g) Split into only two non-empty elements:
The return value contains these 2 elements:
<ONE>< TWO,, , THREE,,>
1h) Split into only two non-whitespace elements with whitespace trimmed:
The return value contains these 2 elements:
<ONE><TWO,, , THREE,,>
2) Split a string delimited by another string:
The original string is: "[stop]ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] ".
The delimiter string is: "[stop]".
2a) Return all elements:
The return value contains these 9 elements:
<><ONE>< ><TWO ><>< ><THREE><>< >
2b) Return all elements with whitespace trimmed:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>
2c) Return all non-empty elements:
The return value contains these 6 elements:
<ONE>< ><TWO >< ><THREE>< >
2d) Return all non-whitespace elements with whitespace trimmed:
The return value contains these 3 elements:
<ONE><TWO><THREE>
2e) Split into only two elements:
The return value contains these 2 elements:
<><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] >
2f) Split into only two elements with whitespace trimmed:
The return value contains these 2 elements:
<><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop]>
2g) Split into only two non-empty elements:
The return value contains these 2 elements:
<ONE>< [stop]TWO [stop][stop] [stop]THREE[stop][stop] >
2h) Split into only two non-whitespace elements with whitespace trimmed:
The return value contains these 2 elements:
<ONE><TWO [stop][stop] [stop]THREE[stop][stop]>
*/
// This example demonstrates the String.Split() methods that use
// the StringSplitOptions enumeration.
// Display the array of separated strings using a local function
let show (entries: string[]) =
printfn $"The return value contains these {entries.Length} elements:"
for entry in entries do
printf $"<{entry}>"
printf "\n\n"
// Example 1: Split a string delimited by characters
printfn "1) Split a string delimited by characters:\n"
let s1 = ",ONE,, TWO,, , THREE,,"
let charSeparators = [| ',' |]
printfn $"The original string is: \"{s1}\"."
printfn $"The delimiter character is: '{charSeparators[0]}'.\n"
// Split the string and return all elements
printfn "1a) Return all elements:"
let result = s1.Split(charSeparators, StringSplitOptions.None)
show result
// Split the string and return all elements with whitespace trimmed
printfn "1b) Return all elements with whitespace trimmed:"
let result = s1.Split(charSeparators, StringSplitOptions.TrimEntries)
show result
// Split the string and return all non-empty elements
printfn "1c) Return all non-empty elements:"
let result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries)
show result
// Split the string and return all non-whitespace elements with whitespace trimmed
printfn "1d) Return all non-whitespace elements with whitespace trimmed:"
let result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)
show result
// Split the string into only two elements, keeping the remainder in the last match
printfn "1e) Split into only two elements:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.None)
show result
// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
printfn "1f) Split into only two elements with whitespace trimmed:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.TrimEntries)
show result
// Split the string into only two non-empty elements, keeping the remainder in the last match
printfn "1g) Split into only two non-empty elements:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
show result
// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
printfn "1h) Split into only two non-whitespace elements with whitespace trimmed:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)
show result
// Example 2: Split a string delimited by another string
printfn "2) Split a string delimited by another string:\n"
let s2 = "[stop]" +
"ONE[stop] [stop]" +
"TWO [stop][stop] [stop]" +
"THREE[stop][stop] "
let stringSeparators = [| "[stop]" |]
printfn $"The original string is: \"{s2}\"."
printfn $"The delimiter string is: \"{stringSeparators[0]}\".\n"
// Split the string and return all elements
printfn "2a) Return all elements:"
let result = s2.Split(stringSeparators, StringSplitOptions.None)
show result
// Split the string and return all elements with whitespace trimmed
printfn "2b) Return all elements with whitespace trimmed:"
let result = s2.Split(stringSeparators, StringSplitOptions.TrimEntries)
show result
// Split the string and return all non-empty elements
printfn "2c) Return all non-empty elements:"
let result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)
show result
// Split the string and return all non-whitespace elements with whitespace trimmed
printfn "2d) Return all non-whitespace elements with whitespace trimmed:"
let result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)
show result
// Split the string into only two elements, keeping the remainder in the last match
printfn "2e) Split into only two elements:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.None)
show result
// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
printfn "2f) Split into only two elements with whitespace trimmed:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.TrimEntries)
show result
// Split the string into only two non-empty elements, keeping the remainder in the last match
printfn "2g) Split into only two non-empty elements:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
show result
// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
printfn "2h) Split into only two non-whitespace elements with whitespace trimmed:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)
show result
(*
This example produces the following results:
1) Split a string delimited by characters:
The original string is: ",ONE,, TWO,, , THREE,,".
The delimiter character is: ','.
1a) Return all elements:
The return value contains these 9 elements:
<><ONE><>< TWO><>< >< THREE><><>
1b) Return all elements with whitespace trimmed:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>
1c) Return all non-empty elements:
The return value contains these 4 elements:
<ONE>< TWO>< >< THREE>
1d) Return all non-whitespace elements with whitespace trimmed:
The return value contains these 3 elements:
<ONE><TWO><THREE>
1e) Split into only two elements:
The return value contains these 2 elements:
<><ONE,, TWO,, , THREE,,>
1f) Split into only two elements with whitespace trimmed:
The return value contains these 2 elements:
<><ONE,, TWO,, , THREE,,>
1g) Split into only two non-empty elements:
The return value contains these 2 elements:
<ONE>< TWO,, , THREE,,>
1h) Split into only two non-whitespace elements with whitespace trimmed:
The return value contains these 2 elements:
<ONE><TWO,, , THREE,,>
2) Split a string delimited by another string:
The original string is: "[stop]ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] ".
The delimiter string is: "[stop]".
2a) Return all elements:
The return value contains these 9 elements:
<><ONE>< ><TWO ><>< ><THREE><>< >
2b) Return all elements with whitespace trimmed:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>
2c) Return all non-empty elements:
The return value contains these 6 elements:
<ONE>< ><TWO >< ><THREE>< >
2d) Return all non-whitespace elements with whitespace trimmed:
The return value contains these 3 elements:
<ONE><TWO><THREE>
2e) Split into only two elements:
The return value contains these 2 elements:
<><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] >
2f) Split into only two elements with whitespace trimmed:
The return value contains these 2 elements:
<><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop]>
2g) Split into only two non-empty elements:
The return value contains these 2 elements:
<ONE>< [stop]TWO [stop][stop] [stop]THREE[stop][stop] >
2h) Split into only two non-whitespace elements with whitespace trimmed:
The return value contains these 2 elements:
<ONE><TWO [stop][stop] [stop]THREE[stop][stop]>
*)
Public Shared Sub StringSplitOptionsExamples()
' This example demonstrates the String.Split() methods that use
' the StringSplitOptions enumeration.
' Example 1: Split a string delimited by characters
Console.WriteLine("1) Split a string delimited by characters:" & vbCrLf)
Dim s1 As String = ",ONE,, TWO,, , THREE,,"
Dim charSeparators() As Char = {","c}
Dim result() As String
Console.WriteLine("The original string is: ""{0}"".", s1)
Console.WriteLine("The delimiter character is: '{0}'." & vbCrLf, charSeparators(0))
' Split the string and return all elements
Console.WriteLine("1a) Return all elements:")
result = s1.Split(charSeparators, StringSplitOptions.None)
Show(result)
' Split the string and return all elements with whitespace trimmed
Console.WriteLine("1b) Return all elements with whitespace trimmed:")
result = s1.Split(charSeparators, StringSplitOptions.TrimEntries)
Show(result)
' Split the string and return all non-empty elements
Console.WriteLine("1c) Return all non-empty elements:")
result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries)
Show(result)
' Split the string and return all non-whitespace elements with whitespace trimmed
Console.WriteLine("1d) Return all non-whitespace elements with whitespace trimmed:")
result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries)
Show(result)
' Split the string into only two elements, keeping the remainder in the last match
Console.WriteLine("1e) Split into only two elements:")
result = s1.Split(charSeparators, 2, StringSplitOptions.None)
Show(result)
' Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("1f) Split into only two elements with whitespace trimmed:")
result = s1.Split(charSeparators, 2, StringSplitOptions.TrimEntries)
Show(result)
' Split the string into only two non-empty elements, keeping the remainder in the last match
Console.WriteLine("1g) Split into only two non-empty elements:")
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
Show(result)
' Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("1h) Split into only two non-whitespace elements with whitespace trimmed:")
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries)
Show(result)
' Example 2: Split a string delimited by another string
Console.WriteLine("2) Split a string delimited by another string:" & vbCrLf)
Dim s2 As String = "[stop]" +
"ONE[stop] [stop]" +
"TWO [stop][stop] [stop]" +
"THREE[stop][stop] "
Dim stringSeparators() As String = {"[stop]"}
Console.WriteLine("The original string is: ""{0}"".", s2)
Console.WriteLine("The delimiter string is: ""{0}""." & vbCrLf, stringSeparators(0))
' Split the string and return all elements
Console.WriteLine("2a) Return all elements:")
result = s2.Split(stringSeparators, StringSplitOptions.None)
Show(result)
' Split the string and return all elements with whitespace trimmed
Console.WriteLine("2b) Return all elements with whitespace trimmed:")
result = s2.Split(stringSeparators, StringSplitOptions.TrimEntries)
Show(result)
' Split the string and return all non-empty elements
Console.WriteLine("2c) Return all non-empty elements:")
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)
Show(result)
' Split the string and return all non-whitespace elements with whitespace trimmed
Console.WriteLine("2d) Return all non-whitespace elements with whitespace trimmed:")
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries)
Show(result)
' Split the string into only two elements, keeping the remainder in the last match
Console.WriteLine("2e) Split into only two elements:")
result = s2.Split(stringSeparators, 2, StringSplitOptions.None)
Show(result)
' Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("2f) Split into only two elements with whitespace trimmed:")
result = s2.Split(stringSeparators, 2, StringSplitOptions.TrimEntries)
Show(result)
' Split the string into only two non-empty elements, keeping the remainder in the last match
Console.WriteLine("2g) Split into only two non-empty elements:")
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
Show(result)
' Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("2h) Split into only two non-whitespace elements with whitespace trimmed:")
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries)
Show(result)
End Sub
' Display the array of separated strings.
Public Shared Sub Show(ByVal entries() As String)
Console.WriteLine("The return value contains these {0} elements:", entries.Length)
Dim entry As String
For Each entry In entries
Console.Write("<{0}>", entry)
Next entry
Console.Write(vbCrLf & vbCrLf)
End Sub
'This example produces the following results:
'
' 1) Split a string delimited by characters:
'
' The original string is: ",ONE,, TWO,, , THREE,,".
' The delimiter character is: ','.
'
' 1a) Return all elements:
' The return value contains these 9 elements:
' <><ONE><>< TWO><>< >< THREE><><>
'
' 1b) Return all elements with whitespace trimmed:
' The return value contains these 9 elements:
' <><ONE><><TWO><><><THREE><><>
'
' 1c) Return all non-empty elements:
' The return value contains these 4 elements:
' <ONE>< TWO>< >< THREE>
'
' 1d) Return all non-whitespace elements with whitespace trimmed:
' The return value contains these 3 elements:
' <ONE><TWO><THREE>
'
' 1e) Split into only two elements:
' The return value contains these 2 elements:
' <><ONE,, TWO,, , THREE,,>
'
' 1f) Split into only two elements with whitespace trimmed:
' The return value contains these 2 elements:
' <><ONE,, TWO,, , THREE,,>
'
' 1g) Split into only two non-empty elements:
' The return value contains these 2 elements:
' <ONE>< TWO,, , THREE,,>
'
' 1h) Split into only two non-whitespace elements with whitespace trimmed:
' The return value contains these 2 elements:
' <ONE><TWO,, , THREE,,>
'
' 2) Split a string delimited by another string:
'
' The original string is: "[stop]ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] ".
' The delimiter string is: "[stop]".
'
' 2a) Return all elements:
' The return value contains these 9 elements:
' <><ONE>< ><TWO ><>< ><THREE><>< >
'
' 2b) Return all elements with whitespace trimmed:
' The return value contains these 9 elements:
' <><ONE><><TWO><><><THREE><><>
'
' 2c) Return all non-empty elements:
' The return value contains these 6 elements:
' <ONE>< ><TWO >< ><THREE>< >
'
' 2d) Return all non-whitespace elements with whitespace trimmed:
' The return value contains these 3 elements:
' <ONE><TWO><THREE>
'
' 2e) Split into only two elements:
' The return value contains these 2 elements:
' <><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] >
'
' 2f) Split into only two elements with whitespace trimmed:
' The return value contains these 2 elements:
' <><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop]>
'
' 2g) Split into only two non-empty elements:
' The return value contains these 2 elements:
' <ONE>< [stop]TWO [stop][stop] [stop]THREE[stop][stop] >
'
' 2h) Split into only two non-whitespace elements with whitespace trimmed:
' The return value contains these 2 elements:
' <ONE><TWO [stop][stop] [stop]THREE[stop][stop]>
'
Poznámky
Znaky oddělovače nejsou zahrnuty do prvků vráceného pole.
Pokud tato instance neobsahuje žádné znaky v separatornebo count parametr je 1, vrácená pole se skládá z jednoho prvku, který obsahuje tuto instanci.
separator Pokud je null parametr nebo neobsahuje žádné znaky, předpokládá se, že prázdné znaky jsou oddělovači. Prázdné znaky jsou definovány standardem Unicode a Char.IsWhiteSpace metoda vrátí true , pokud jsou předány do něj.
Chcete-li předat null parametr char[] separator , je nutné určit typ null , který má zrušit nejednoznačnost volání z některých jiných přetížení, například Split(String[], Int32, StringSplitOptions). Následující příklad ukazuje několik způsobů, jak jednoznačně identifikovat toto přetížení.
string phrase = "The quick brown fox";
_ = phrase.Split(default(char[]), 3, StringSplitOptions.RemoveEmptyEntries);
_ = phrase.Split((char[]?)null, 3, StringSplitOptions.RemoveEmptyEntries);
_ = phrase.Split(null as char[], 3, StringSplitOptions.RemoveEmptyEntries);
let phrase = "The quick brown fox"
phrase.Split(Unchecked.defaultof<char[]>, 3, StringSplitOptions.RemoveEmptyEntries) |> ignore
phrase.Split(null :> char[], 3, StringSplitOptions.RemoveEmptyEntries) |> ignore
phrase.Split((null: char[]), 3, StringSplitOptions.RemoveEmptyEntries) |> ignore
Dim phrase As String = "The quick brown fox"
Dim words() As String
words = phrase.Split(TryCast(Nothing, Char()), 3,
StringSplitOptions.RemoveEmptyEntries)
words = phrase.Split(New Char() {}, 3,
StringSplitOptions.RemoveEmptyEntries)
count Pokud je parametr nula nebo options je RemoveEmptyEntries parametr a délka této instance je nula, vrátí se prázdné pole.
Každý prvek separator definuje samostatný znak oddělovače.
options Pokud je Noneparametr a dva oddělovače jsou sousední nebo oddělovač je nalezen na začátku nebo na konci této instance, odpovídající prvek pole obsahuje Empty.
Pokud je v této instanci více než count podřetěžců, vrátí se první podřetěžce minus 1 v prvních countcount mínus 1 prvcích návratové hodnoty a zbývající znaky v této instanci se vrátí v posledním prvku návratové hodnoty.
Pokud count je větší než počet podřetětců, vrátí se dostupné podřetětězení a nevyvolá se žádná výjimka.
Důležité informace o výkonu
Metody Split přidělují paměť pro vrácený maticový objekt a String objekt pro každý prvek pole. Pokud vaše aplikace vyžaduje optimální výkon nebo pokud je správa přidělení paměti ve vaší aplikaci důležitá, zvažte použití IndexOf metody nebo IndexOfAny metody a volitelně Compare vyhledejte podřetězce v řetězci.
Pokud rozdělujete řetězec na znak oddělovače, pomocí IndexOf nebo IndexOfAny metody vyhledejte v řetězci znak oddělovače. Pokud rozdělujete řetězec na řetězec oddělovače, použijte IndexOf metodu nebo IndexOfAny vyhledejte první znak řetězce oddělovače. Pak pomocí Compare metody určete, zda se znaky za tímto prvním znakem rovnají zbývajícím znakům řetězce oddělovače.
Kromě toho platí, že pokud se ke rozdělení řetězců ve více Split voláních metod používá stejná sada znaků, zvažte vytvoření jednoho pole a odkazování na ni v každém volání metody. Tím se výrazně sníží režijní náklady na každé volání metody.
Poznámky pro volající
V rozhraní .NET Framework 3.5 a starších verzích, pokud Split(Char[]) je metoda předána separator nebo null neobsahuje žádné znaky, metoda používá mírně odlišnou sadu prázdných znaků k rozdělení řetězce, než Trim(Char[]) metoda provádí oříznutí řetězce. Počínaje rozhraním .NET Framework 4 používají obě metody stejnou sadu prázdných znaků Unicode.
Platí pro
Split(Char, Int32, StringSplitOptions)
- Zdroj:
- String.Manipulation.cs
- Zdroj:
- String.Manipulation.cs
- Zdroj:
- String.Manipulation.cs
- Zdroj:
- String.Manipulation.cs
Rozdělí řetězec na maximální počet podřetězců na základě zadaného oddělovače znaků, volitelně vynechá prázdné podřetězce z výsledku.
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()
Parametry
- separator
- Char
Znak, který odděluje podřetětěce v této instanci.
- count
- Int32
Maximální počet prvků očekávaných v poli.
- options
- StringSplitOptions
Bitové kombinace hodnot výčtu, která určuje, zda se mají oříznout podřetězce a zahrnout prázdné podřetězce.
Návraty
Pole, které obsahuje nejvýše count podřetětěce z této instance, které jsou odděleny .separator
Poznámky
Pokud je řetězec již rozdělený count – 1krát, ale konec řetězce nebyl dosažen, bude poslední řetězec ve vráceném poli obsahovat zbývající koncový podřetězc této instance, nedotčený.
Platí pro
Split(String[], StringSplitOptions)
- Zdroj:
- String.Manipulation.cs
- Zdroj:
- String.Manipulation.cs
- Zdroj:
- String.Manipulation.cs
- Zdroj:
- String.Manipulation.cs
Rozdělí řetězec na podřetězce na základě zadaného řetězce s oddělovači a volitelně i možností.
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()
Parametry
- separator
- String[]
Pole řetězců, které odděluje podřetězce v tomto řetězci, prázdné pole, které neobsahuje žádné oddělovače, nebo null.
- options
- StringSplitOptions
Bitové kombinace hodnot výčtu, která určuje, zda se mají oříznout podřetězce a zahrnout prázdné podřetězce.
Návraty
Matice, jejíž prvky obsahují podřetězce v tomto řetězci, které jsou odděleny jedním nebo více řetězci v separator. Další informace najdete v části Poznámky.
- Atributy
Výjimky
options není jednou z StringSplitOptions hodnot.
Příklady
Následující příklad ukazuje rozdíl v polích vrácených voláním metody řetězce String.Split(String[], StringSplitOptions) s jeho options parametrem rovna StringSplitOptions.None a StringSplitOptions.RemoveEmptyEntries.
string source = "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]";
string[] stringSeparators = new string[] { "[stop]" };
string[] result;
// Display the original string and delimiter string.
Console.WriteLine($"Splitting the string:\n \"{source}\".");
Console.WriteLine();
Console.WriteLine($"Using the delimiter string:\n \"{stringSeparators[0]}\"");
Console.WriteLine();
// Split a string delimited by another string and return all elements.
result = source.Split(stringSeparators, StringSplitOptions.None);
Console.WriteLine($"Result including all elements ({result.Length} elements):");
Console.Write(" ");
foreach (string s in result)
{
Console.Write("'{0}' ", String.IsNullOrEmpty(s) ? "<>" : s);
}
Console.WriteLine();
Console.WriteLine();
// Split delimited by another string and return all non-empty elements.
result = source.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);
Console.WriteLine($"Result including non-empty elements ({result.Length} elements):");
Console.Write(" ");
foreach (string s in result)
{
Console.Write("'{0}' ", String.IsNullOrEmpty(s) ? "<>" : s);
}
Console.WriteLine();
// The example displays the following output:
// Splitting the string:
// "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".
//
// Using the delimiter string:
// "[stop]"
//
// Result including all elements (9 elements):
// '<>' 'ONE' '<>' 'TWO' '<>' '<>' 'THREE' '<>' '<>'
//
// Result including non-empty elements (3 elements):
// 'ONE' 'TWO' 'THREE'
let source = "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]"
let stringSeparators = [| "[stop]" |]
// Display the original string and delimiter string.
printfn $"Splitting the string:\n \"{source}\".\n"
printfn $"Using the delimiter string:\n \"{stringSeparators[0]}\"\n"
// Split a string delimited by another string and return all elements.
let result = source.Split(stringSeparators, StringSplitOptions.None)
printfn $"Result including all elements ({result.Length} elements):"
printf " "
for s in result do
printf $"""'{if String.IsNullOrEmpty s then "<>" else s}' """
printfn "\n"
// Split delimited by another string and return all non-empty elements.
let result = source.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)
Console.WriteLine($"Result including non-empty elements ({result.Length} elements):")
printf " "
for s in result do
printf $"""'{if String.IsNullOrEmpty s then "<>" else s}' """
printfn ""
// The example displays the following output:
// Splitting the string:
// "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".
//
// Using the delimiter string:
// "[stop]"
//
// let result including all elements (9 elements):
// '<>' 'ONE' '<>' 'TWO' '<>' '<>' 'THREE' '<>' '<>'
//
// let result including non-empty elements (3 elements):
// 'ONE' 'TWO' 'THREE'
Dim source As String = "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]"
Dim stringSeparators() As String = {"[stop]"}
Dim result() As String
' Display the original string and delimiter string.
Console.WriteLine("Splitting the string:{0} '{1}'.", vbCrLf, source)
Console.WriteLine()
Console.WriteLine("Using the delimiter string:{0} '{1}'.",
vbCrLf, stringSeparators(0))
Console.WriteLine()
' Split a string delimited by another string and return all elements.
result = source.Split(stringSeparators, StringSplitOptions.None)
Console.WriteLine("Result including all elements ({0} elements):",
result.Length)
Console.Write(" ")
For Each s As String In result
Console.Write("'{0}' ", IIf(String.IsNullOrEmpty(s), "<>", s))
Next
Console.WriteLine()
Console.WriteLine()
' Split delimited by another string and return all non-empty elements.
result = source.Split(stringSeparators,
StringSplitOptions.RemoveEmptyEntries)
Console.WriteLine("Result including non-empty elements ({0} elements):",
result.Length)
Console.Write(" ")
For Each s As String In result
Console.Write("'{0}' ", IIf(String.IsNullOrEmpty(s), "<>", s))
Next
Console.WriteLine()
' The example displays the following output:
' Splitting the string:
' "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".
'
' Using the delimiter string:
' "[stop]"
'
' Result including all elements (9 elements):
' '<>' 'ONE' '<>' 'TWO' '<>' '<>' 'THREE' '<>' '<>'
'
' Result including non-empty elements (3 elements):
' 'ONE' 'TWO' 'THREE'
Následující příklad definuje pole oddělovačů, které obsahují interpunkční znaky a prázdné znaky. Předání tohoto pole spolu s hodnotou StringSplitOptions.RemoveEmptyEntries metody Split(String[], StringSplitOptions) vrátí matici, která se skládá z jednotlivých slov z řetězce.
string[] separators = { ",", ".", "!", "?", ";", ":", " " };
string value = "The handsome, energetic, young dog was playing with his smaller, more lethargic litter mate.";
string[] words = value.Split(separators, StringSplitOptions.RemoveEmptyEntries);
foreach (var word in words)
Console.WriteLine(word);
// The example displays the following output:
// The
// handsome
// energetic
// young
// dog
// was
// playing
// with
// his
// smaller
// more
// lethargic
// litter
// mate
let separators = [| ","; "."; "!"; "?"; ""; ":"; " " |]
let value = "The handsome, energetic, young dog was playing with his smaller, more lethargic litter mate."
let words = value.Split(separators, StringSplitOptions.RemoveEmptyEntries)
for word in words do
printfn $"${word}"
// The example displays the following output:
// The
// handsome
// energetic
// young
// dog
// was
// playing
// with
// his
// smaller
// more
// lethargic
// litter
// mate
Dim separators() As String = {",", ".", "!", "?", ";", ":", " "}
Dim value As String = "The handsome, energetic, young dog was playing with his smaller, more lethargic litter mate."
Dim words() As String = value.Split(separators, StringSplitOptions.RemoveEmptyEntries)
For Each word In words
Console.WriteLine(word)
Next
End Sub
' The example displays the following output:
'
' The
' handsome
' energetic
' young
' dog
' was
' playing
' with
' his
' smaller
' more
' lethargic
' litter
' mate
Všimněte si, že metoda je volána s argumentem options nastaveným na StringSplitOptions.RemoveEmptyEntries. Tím zabrání vrácené matici, aby zahrnovala String.Empty hodnoty, které představují shodu prázdných podřetězí mezi interpunkčními znaménkami a prázdnými znaky.
Poznámky
Pokud je řetězec oddělený známou sadou řetězců, můžete ji použít Split k jeho oddělení do podřetězců.
Řetězce oddělovače nejsou zahrnuty do prvků vráceného pole. Pokud například separator matice obsahuje řetězec "--" a hodnota aktuální instance řetězce je "aa--bb--cc", vrátí metoda matici, která obsahuje tři prvky: "aa", "bb" a "cc".
Pokud tato instance neobsahuje žádný z řetězců v separator, vrácené pole se skládá z jednoho prvku, který obsahuje tuto instanci.
options Pokud je RemoveEmptyEntries parametr a délka této instance je nula, metoda vrátí prázdné pole.
Každý prvek separator definuje samostatný oddělovač, který se skládá z jednoho nebo více znaků.
options Pokud argument je Nonea dva oddělovače jsou sousední nebo oddělovač je nalezen na začátku nebo na konci této instance, odpovídající prvek pole obsahuje String.Empty. Pokud například separator obsahuje dva prvky, "-" a "_", hodnota instance řetězce je -_aa-_, a hodnota argumentu options je None, metoda vrátí pole řetězce s následujícími pěti prvky:
String.Empty, který představuje prázdný řetězec, který předchází podřetězce "-" v indexu 0.
String.Empty, který představuje prázdný řetězec mezi podřetězcem "-" v indexu 0 a podřetězcem "_" v indexu 1.
"aa".
String.Empty, který představuje prázdný řetězec, který následuje za podřetězcem "-" v indexu 4.
String.Empty, který představuje prázdný řetězec, který následuje za podřetězcem "_" v indexu 5.
Pole oddělovače
Pokud se některý z prvků separator skládá z více znaků, považuje se celý podřetězen za oddělovač. Pokud je například jeden z prvků v separator hodnotě "10", pokusí se rozdělit řetězec "This10is10a10string". Vrátí následující pole se čtyřmi prvky: { "This", "is", "a", "string". }.
separator Pokud je null parametr nebo neobsahuje žádné neprázdné řetězce, předpokládá se, že prázdné znaky jsou oddělovačem. Prázdné znaky jsou definovány standardem Unicode a Char.IsWhiteSpace metoda vrátí true , pokud jsou předány do něj.
Chcete-li předat null parametr string[] separator , je nutné určit typ null , který má zrušit nejednoznačnost volání z některých jiných přetížení, například Split(Char[], StringSplitOptions). Následující příklad ukazuje několik způsobů, jak jednoznačně identifikovat toto přetížení.
string phrase = "The quick brown fox";
_ = phrase.Split(default(string[]), StringSplitOptions.RemoveEmptyEntries);
_ = phrase.Split((string[]?)null, StringSplitOptions.RemoveEmptyEntries);
_ = phrase.Split(null as string[], StringSplitOptions.RemoveEmptyEntries);
let phrase = "The quick brown fox"
phrase.Split(Unchecked.defaultof<string[]>, StringSplitOptions.RemoveEmptyEntries) |> ignore
phrase.Split(null :> string[], StringSplitOptions.RemoveEmptyEntries) |> ignore
phrase.Split((null: string[]), StringSplitOptions.RemoveEmptyEntries) |> ignore
Dim phrase As String = "The quick brown fox"
Dim words() As String
words = phrase.Split(TryCast(Nothing, String()),
StringSplitOptions.RemoveEmptyEntries)
words = phrase.Split(New String() {},
StringSplitOptions.RemoveEmptyEntries)
Podrobnosti porovnání
Metoda Split extrahuje podřetězce v tomto řetězci, které jsou oddělené jedním nebo více řetězci v parametru separator , a vrátí tyto podřetězce jako prvky pole.
Metoda Split hledá oddělovače provedením porovnání pomocí pravidel řazení s rozlišováním malých a velkých písmen. Další informace o slovech, řetězcích a řadových řazeních najdete ve výčtu System.Globalization.CompareOptions .
Metoda Split ignoruje jakýkoli prvek, jehož separator hodnota je null nebo prázdný řetězec ("").
Aby nedocházelo k nejednoznačným výsledkům, pokud řetězce mají separator společné znaky, Split operace pokračuje od začátku do konce hodnoty instance a odpovídá prvnímu prvku, separator který se rovná oddělovači v instanci. Pořadí, ve kterém jsou v instanci zjištěny podřetěděce, má přednost před pořadím prvků v separator.
Představte si například instanci, jejíž hodnota je abcdef. Pokud byl první prvek " separator ef" a druhý prvek byl "bcde", výsledkem operace rozdělení by byla řetězcová matice, která obsahuje dva prvky, "a" a "f". Důvodem je to, že podřetězi v instanci "bcde", je zjištěn a odpovídá prvku před separator výskytem podřetětězi "f".
Pokud byl první prvek separator "bcd" a druhý prvek byl "bc", výsledkem operace rozdělení by byla řetězcová matice, která obsahuje dva prvky, "a" a "ef". Důvodem je to, že "bcd" je první oddělovač, separator který odpovídá oddělovači v instanci. Pokud bylo pořadí oddělovačů obrácené tak, aby první prvek byl "bc" a druhý prvek byl "bcd", výsledkem by byla řetězcová matice, která obsahuje dva prvky, "a" a "def".
Důležité informace o výkonu
Metody Split přidělují paměť pro vrácený maticový objekt a String objekt pro každý prvek pole. Pokud vaše aplikace vyžaduje optimální výkon nebo pokud je správa přidělení paměti ve vaší aplikaci důležitá, zvažte použití IndexOf metody nebo IndexOfAny metody a volitelně Compare vyhledejte podřetězce v řetězci.
Pokud rozdělujete řetězec na znak oddělovače, pomocí IndexOf nebo IndexOfAny metody vyhledejte v řetězci znak oddělovače. Pokud rozdělujete řetězec na řetězec oddělovače, použijte IndexOf metodu nebo IndexOfAny vyhledejte první znak řetězce oddělovače. Pak pomocí Compare metody určete, zda se znaky za tímto prvním znakem rovnají zbývajícím znakům řetězce oddělovače.
Kromě toho platí, že pokud se ke rozdělení řetězců ve více Split voláních metod používá stejná sada znaků, zvažte vytvoření jednoho pole a odkazování na ni v každém volání metody. Tím se výrazně sníží režijní náklady na každé volání metody.
Poznámky pro volající
V rozhraní .NET Framework 3.5 a starších verzích, pokud Split(Char[]) je metoda předána separator nebo null neobsahuje žádné znaky, metoda používá mírně odlišnou sadu prázdných znaků k rozdělení řetězce, než Trim(Char[]) metoda provádí oříznutí řetězce. Počínaje rozhraním .NET Framework 4 používají obě metody stejnou sadu prázdných znaků Unicode.
Platí pro
Split(String, Int32, StringSplitOptions)
- Zdroj:
- String.Manipulation.cs
- Zdroj:
- String.Manipulation.cs
- Zdroj:
- String.Manipulation.cs
- Zdroj:
- String.Manipulation.cs
Rozdělí řetězec na maximální počet podřetězců na základě zadaného oddělovacího řetězce a volitelně možností.
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()
Parametry
- separator
- String
Řetězec, který odděluje podřetězce v této instanci.
- count
- Int32
Maximální počet prvků očekávaných v poli.
- options
- StringSplitOptions
Bitové kombinace hodnot výčtu, která určuje, zda se mají oříznout podřetězce a zahrnout prázdné podřetězce.
Návraty
Pole, které obsahuje nejvýše count podřetětěce z této instance, které jsou odděleny .separator
Poznámky
Pokud je řetězec již rozdělený count – 1krát, ale konec řetězce nebyl dosažen, bude poslední řetězec ve vráceném poli obsahovat zbývající koncový podřetězc této instance, nedotčený.
Platí pro
Split(Char[], StringSplitOptions)
- Zdroj:
- String.Manipulation.cs
- Zdroj:
- String.Manipulation.cs
- Zdroj:
- String.Manipulation.cs
- Zdroj:
- String.Manipulation.cs
Rozdělí řetězec na podřetězce na základě zadaných znaků a možností s oddělovači.
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()
Parametry
- separator
- Char[]
Pole znaků, které odděluje podřetězce v tomto řetězci, prázdné pole, které neobsahuje žádné oddělovače nebo null.
- options
- StringSplitOptions
Bitové kombinace hodnot výčtu, která určuje, zda se mají oříznout podřetězce a zahrnout prázdné podřetězce.
Návraty
Pole, jehož prvky obsahují podřetězce v tomto řetězci, které jsou odděleny jedním nebo více znaky v separator. Další informace najdete v části Poznámky.
- Atributy
Výjimky
options není jednou z StringSplitOptions hodnot.
Příklady
Následující příklad používá StringSplitOptions výčet k zahrnutí nebo vyloučení podřetězdců vygenerovaných metodou Split .
// This example demonstrates the String.Split() methods that use
// the StringSplitOptions enumeration.
// Example 1: Split a string delimited by characters
Console.WriteLine("1) Split a string delimited by characters:\n");
string s1 = ",ONE,, TWO,, , THREE,,";
char[] charSeparators = new char[] { ',' };
string[] result;
Console.WriteLine($"The original string is: \"{s1}\".");
Console.WriteLine($"The delimiter character is: '{charSeparators[0]}'.\n");
// Split the string and return all elements
Console.WriteLine("1a) Return all elements:");
result = s1.Split(charSeparators, StringSplitOptions.None);
Show(result);
// Split the string and return all elements with whitespace trimmed
Console.WriteLine("1b) Return all elements with whitespace trimmed:");
result = s1.Split(charSeparators, StringSplitOptions.TrimEntries);
Show(result);
// Split the string and return all non-empty elements
Console.WriteLine("1c) Return all non-empty elements:");
result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// Split the string and return all non-whitespace elements with whitespace trimmed
Console.WriteLine("1d) Return all non-whitespace elements with whitespace trimmed:");
result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
Show(result);
// Split the string into only two elements, keeping the remainder in the last match
Console.WriteLine("1e) Split into only two elements:");
result = s1.Split(charSeparators, 2, StringSplitOptions.None);
Show(result);
// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("1f) Split into only two elements with whitespace trimmed:");
result = s1.Split(charSeparators, 2, StringSplitOptions.TrimEntries);
Show(result);
// Split the string into only two non-empty elements, keeping the remainder in the last match
Console.WriteLine("1g) Split into only two non-empty elements:");
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("1h) Split into only two non-whitespace elements with whitespace trimmed:");
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
Show(result);
// Example 2: Split a string delimited by another string
Console.WriteLine("2) Split a string delimited by another string:\n");
string s2 = "[stop]" +
"ONE[stop] [stop]" +
"TWO [stop][stop] [stop]" +
"THREE[stop][stop] ";
string[] stringSeparators = new string[] { "[stop]" };
Console.WriteLine($"The original string is: \"{s2}\".");
Console.WriteLine($"The delimiter string is: \"{stringSeparators[0]}\".\n");
// Split the string and return all elements
Console.WriteLine("2a) Return all elements:");
result = s2.Split(stringSeparators, StringSplitOptions.None);
Show(result);
// Split the string and return all elements with whitespace trimmed
Console.WriteLine("2b) Return all elements with whitespace trimmed:");
result = s2.Split(stringSeparators, StringSplitOptions.TrimEntries);
Show(result);
// Split the string and return all non-empty elements
Console.WriteLine("2c) Return all non-empty elements:");
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// Split the string and return all non-whitespace elements with whitespace trimmed
Console.WriteLine("2d) Return all non-whitespace elements with whitespace trimmed:");
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
Show(result);
// Split the string into only two elements, keeping the remainder in the last match
Console.WriteLine("2e) Split into only two elements:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.None);
Show(result);
// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("2f) Split into only two elements with whitespace trimmed:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.TrimEntries);
Show(result);
// Split the string into only two non-empty elements, keeping the remainder in the last match
Console.WriteLine("2g) Split into only two non-empty elements:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("2h) Split into only two non-whitespace elements with whitespace trimmed:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
Show(result);
// Display the array of separated strings using a local function
void Show(string[] entries)
{
Console.WriteLine($"The return value contains these {entries.Length} elements:");
foreach (string entry in entries)
{
Console.Write($"<{entry}>");
}
Console.Write("\n\n");
}
/*
This example produces the following results:
1) Split a string delimited by characters:
The original string is: ",ONE,, TWO,, , THREE,,".
The delimiter character is: ','.
1a) Return all elements:
The return value contains these 9 elements:
<><ONE><>< TWO><>< >< THREE><><>
1b) Return all elements with whitespace trimmed:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>
1c) Return all non-empty elements:
The return value contains these 4 elements:
<ONE>< TWO>< >< THREE>
1d) Return all non-whitespace elements with whitespace trimmed:
The return value contains these 3 elements:
<ONE><TWO><THREE>
1e) Split into only two elements:
The return value contains these 2 elements:
<><ONE,, TWO,, , THREE,,>
1f) Split into only two elements with whitespace trimmed:
The return value contains these 2 elements:
<><ONE,, TWO,, , THREE,,>
1g) Split into only two non-empty elements:
The return value contains these 2 elements:
<ONE>< TWO,, , THREE,,>
1h) Split into only two non-whitespace elements with whitespace trimmed:
The return value contains these 2 elements:
<ONE><TWO,, , THREE,,>
2) Split a string delimited by another string:
The original string is: "[stop]ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] ".
The delimiter string is: "[stop]".
2a) Return all elements:
The return value contains these 9 elements:
<><ONE>< ><TWO ><>< ><THREE><>< >
2b) Return all elements with whitespace trimmed:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>
2c) Return all non-empty elements:
The return value contains these 6 elements:
<ONE>< ><TWO >< ><THREE>< >
2d) Return all non-whitespace elements with whitespace trimmed:
The return value contains these 3 elements:
<ONE><TWO><THREE>
2e) Split into only two elements:
The return value contains these 2 elements:
<><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] >
2f) Split into only two elements with whitespace trimmed:
The return value contains these 2 elements:
<><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop]>
2g) Split into only two non-empty elements:
The return value contains these 2 elements:
<ONE>< [stop]TWO [stop][stop] [stop]THREE[stop][stop] >
2h) Split into only two non-whitespace elements with whitespace trimmed:
The return value contains these 2 elements:
<ONE><TWO [stop][stop] [stop]THREE[stop][stop]>
*/
// This example demonstrates the String.Split() methods that use
// the StringSplitOptions enumeration.
// Display the array of separated strings using a local function
let show (entries: string[]) =
printfn $"The return value contains these {entries.Length} elements:"
for entry in entries do
printf $"<{entry}>"
printf "\n\n"
// Example 1: Split a string delimited by characters
printfn "1) Split a string delimited by characters:\n"
let s1 = ",ONE,, TWO,, , THREE,,"
let charSeparators = [| ',' |]
printfn $"The original string is: \"{s1}\"."
printfn $"The delimiter character is: '{charSeparators[0]}'.\n"
// Split the string and return all elements
printfn "1a) Return all elements:"
let result = s1.Split(charSeparators, StringSplitOptions.None)
show result
// Split the string and return all elements with whitespace trimmed
printfn "1b) Return all elements with whitespace trimmed:"
let result = s1.Split(charSeparators, StringSplitOptions.TrimEntries)
show result
// Split the string and return all non-empty elements
printfn "1c) Return all non-empty elements:"
let result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries)
show result
// Split the string and return all non-whitespace elements with whitespace trimmed
printfn "1d) Return all non-whitespace elements with whitespace trimmed:"
let result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)
show result
// Split the string into only two elements, keeping the remainder in the last match
printfn "1e) Split into only two elements:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.None)
show result
// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
printfn "1f) Split into only two elements with whitespace trimmed:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.TrimEntries)
show result
// Split the string into only two non-empty elements, keeping the remainder in the last match
printfn "1g) Split into only two non-empty elements:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
show result
// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
printfn "1h) Split into only two non-whitespace elements with whitespace trimmed:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)
show result
// Example 2: Split a string delimited by another string
printfn "2) Split a string delimited by another string:\n"
let s2 = "[stop]" +
"ONE[stop] [stop]" +
"TWO [stop][stop] [stop]" +
"THREE[stop][stop] "
let stringSeparators = [| "[stop]" |]
printfn $"The original string is: \"{s2}\"."
printfn $"The delimiter string is: \"{stringSeparators[0]}\".\n"
// Split the string and return all elements
printfn "2a) Return all elements:"
let result = s2.Split(stringSeparators, StringSplitOptions.None)
show result
// Split the string and return all elements with whitespace trimmed
printfn "2b) Return all elements with whitespace trimmed:"
let result = s2.Split(stringSeparators, StringSplitOptions.TrimEntries)
show result
// Split the string and return all non-empty elements
printfn "2c) Return all non-empty elements:"
let result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)
show result
// Split the string and return all non-whitespace elements with whitespace trimmed
printfn "2d) Return all non-whitespace elements with whitespace trimmed:"
let result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)
show result
// Split the string into only two elements, keeping the remainder in the last match
printfn "2e) Split into only two elements:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.None)
show result
// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
printfn "2f) Split into only two elements with whitespace trimmed:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.TrimEntries)
show result
// Split the string into only two non-empty elements, keeping the remainder in the last match
printfn "2g) Split into only two non-empty elements:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
show result
// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
printfn "2h) Split into only two non-whitespace elements with whitespace trimmed:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)
show result
(*
This example produces the following results:
1) Split a string delimited by characters:
The original string is: ",ONE,, TWO,, , THREE,,".
The delimiter character is: ','.
1a) Return all elements:
The return value contains these 9 elements:
<><ONE><>< TWO><>< >< THREE><><>
1b) Return all elements with whitespace trimmed:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>
1c) Return all non-empty elements:
The return value contains these 4 elements:
<ONE>< TWO>< >< THREE>
1d) Return all non-whitespace elements with whitespace trimmed:
The return value contains these 3 elements:
<ONE><TWO><THREE>
1e) Split into only two elements:
The return value contains these 2 elements:
<><ONE,, TWO,, , THREE,,>
1f) Split into only two elements with whitespace trimmed:
The return value contains these 2 elements:
<><ONE,, TWO,, , THREE,,>
1g) Split into only two non-empty elements:
The return value contains these 2 elements:
<ONE>< TWO,, , THREE,,>
1h) Split into only two non-whitespace elements with whitespace trimmed:
The return value contains these 2 elements:
<ONE><TWO,, , THREE,,>
2) Split a string delimited by another string:
The original string is: "[stop]ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] ".
The delimiter string is: "[stop]".
2a) Return all elements:
The return value contains these 9 elements:
<><ONE>< ><TWO ><>< ><THREE><>< >
2b) Return all elements with whitespace trimmed:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>
2c) Return all non-empty elements:
The return value contains these 6 elements:
<ONE>< ><TWO >< ><THREE>< >
2d) Return all non-whitespace elements with whitespace trimmed:
The return value contains these 3 elements:
<ONE><TWO><THREE>
2e) Split into only two elements:
The return value contains these 2 elements:
<><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] >
2f) Split into only two elements with whitespace trimmed:
The return value contains these 2 elements:
<><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop]>
2g) Split into only two non-empty elements:
The return value contains these 2 elements:
<ONE>< [stop]TWO [stop][stop] [stop]THREE[stop][stop] >
2h) Split into only two non-whitespace elements with whitespace trimmed:
The return value contains these 2 elements:
<ONE><TWO [stop][stop] [stop]THREE[stop][stop]>
*)
Public Shared Sub StringSplitOptionsExamples()
' This example demonstrates the String.Split() methods that use
' the StringSplitOptions enumeration.
' Example 1: Split a string delimited by characters
Console.WriteLine("1) Split a string delimited by characters:" & vbCrLf)
Dim s1 As String = ",ONE,, TWO,, , THREE,,"
Dim charSeparators() As Char = {","c}
Dim result() As String
Console.WriteLine("The original string is: ""{0}"".", s1)
Console.WriteLine("The delimiter character is: '{0}'." & vbCrLf, charSeparators(0))
' Split the string and return all elements
Console.WriteLine("1a) Return all elements:")
result = s1.Split(charSeparators, StringSplitOptions.None)
Show(result)
' Split the string and return all elements with whitespace trimmed
Console.WriteLine("1b) Return all elements with whitespace trimmed:")
result = s1.Split(charSeparators, StringSplitOptions.TrimEntries)
Show(result)
' Split the string and return all non-empty elements
Console.WriteLine("1c) Return all non-empty elements:")
result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries)
Show(result)
' Split the string and return all non-whitespace elements with whitespace trimmed
Console.WriteLine("1d) Return all non-whitespace elements with whitespace trimmed:")
result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries)
Show(result)
' Split the string into only two elements, keeping the remainder in the last match
Console.WriteLine("1e) Split into only two elements:")
result = s1.Split(charSeparators, 2, StringSplitOptions.None)
Show(result)
' Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("1f) Split into only two elements with whitespace trimmed:")
result = s1.Split(charSeparators, 2, StringSplitOptions.TrimEntries)
Show(result)
' Split the string into only two non-empty elements, keeping the remainder in the last match
Console.WriteLine("1g) Split into only two non-empty elements:")
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
Show(result)
' Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("1h) Split into only two non-whitespace elements with whitespace trimmed:")
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries)
Show(result)
' Example 2: Split a string delimited by another string
Console.WriteLine("2) Split a string delimited by another string:" & vbCrLf)
Dim s2 As String = "[stop]" +
"ONE[stop] [stop]" +
"TWO [stop][stop] [stop]" +
"THREE[stop][stop] "
Dim stringSeparators() As String = {"[stop]"}
Console.WriteLine("The original string is: ""{0}"".", s2)
Console.WriteLine("The delimiter string is: ""{0}""." & vbCrLf, stringSeparators(0))
' Split the string and return all elements
Console.WriteLine("2a) Return all elements:")
result = s2.Split(stringSeparators, StringSplitOptions.None)
Show(result)
' Split the string and return all elements with whitespace trimmed
Console.WriteLine("2b) Return all elements with whitespace trimmed:")
result = s2.Split(stringSeparators, StringSplitOptions.TrimEntries)
Show(result)
' Split the string and return all non-empty elements
Console.WriteLine("2c) Return all non-empty elements:")
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)
Show(result)
' Split the string and return all non-whitespace elements with whitespace trimmed
Console.WriteLine("2d) Return all non-whitespace elements with whitespace trimmed:")
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries)
Show(result)
' Split the string into only two elements, keeping the remainder in the last match
Console.WriteLine("2e) Split into only two elements:")
result = s2.Split(stringSeparators, 2, StringSplitOptions.None)
Show(result)
' Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("2f) Split into only two elements with whitespace trimmed:")
result = s2.Split(stringSeparators, 2, StringSplitOptions.TrimEntries)
Show(result)
' Split the string into only two non-empty elements, keeping the remainder in the last match
Console.WriteLine("2g) Split into only two non-empty elements:")
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
Show(result)
' Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("2h) Split into only two non-whitespace elements with whitespace trimmed:")
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries)
Show(result)
End Sub
' Display the array of separated strings.
Public Shared Sub Show(ByVal entries() As String)
Console.WriteLine("The return value contains these {0} elements:", entries.Length)
Dim entry As String
For Each entry In entries
Console.Write("<{0}>", entry)
Next entry
Console.Write(vbCrLf & vbCrLf)
End Sub
'This example produces the following results:
'
' 1) Split a string delimited by characters:
'
' The original string is: ",ONE,, TWO,, , THREE,,".
' The delimiter character is: ','.
'
' 1a) Return all elements:
' The return value contains these 9 elements:
' <><ONE><>< TWO><>< >< THREE><><>
'
' 1b) Return all elements with whitespace trimmed:
' The return value contains these 9 elements:
' <><ONE><><TWO><><><THREE><><>
'
' 1c) Return all non-empty elements:
' The return value contains these 4 elements:
' <ONE>< TWO>< >< THREE>
'
' 1d) Return all non-whitespace elements with whitespace trimmed:
' The return value contains these 3 elements:
' <ONE><TWO><THREE>
'
' 1e) Split into only two elements:
' The return value contains these 2 elements:
' <><ONE,, TWO,, , THREE,,>
'
' 1f) Split into only two elements with whitespace trimmed:
' The return value contains these 2 elements:
' <><ONE,, TWO,, , THREE,,>
'
' 1g) Split into only two non-empty elements:
' The return value contains these 2 elements:
' <ONE>< TWO,, , THREE,,>
'
' 1h) Split into only two non-whitespace elements with whitespace trimmed:
' The return value contains these 2 elements:
' <ONE><TWO,, , THREE,,>
'
' 2) Split a string delimited by another string:
'
' The original string is: "[stop]ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] ".
' The delimiter string is: "[stop]".
'
' 2a) Return all elements:
' The return value contains these 9 elements:
' <><ONE>< ><TWO ><>< ><THREE><>< >
'
' 2b) Return all elements with whitespace trimmed:
' The return value contains these 9 elements:
' <><ONE><><TWO><><><THREE><><>
'
' 2c) Return all non-empty elements:
' The return value contains these 6 elements:
' <ONE>< ><TWO >< ><THREE>< >
'
' 2d) Return all non-whitespace elements with whitespace trimmed:
' The return value contains these 3 elements:
' <ONE><TWO><THREE>
'
' 2e) Split into only two elements:
' The return value contains these 2 elements:
' <><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] >
'
' 2f) Split into only two elements with whitespace trimmed:
' The return value contains these 2 elements:
' <><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop]>
'
' 2g) Split into only two non-empty elements:
' The return value contains these 2 elements:
' <ONE>< [stop]TWO [stop][stop] [stop]THREE[stop][stop] >
'
' 2h) Split into only two non-whitespace elements with whitespace trimmed:
' The return value contains these 2 elements:
' <ONE><TWO [stop][stop] [stop]THREE[stop][stop]>
'
Poznámky
Znaky oddělovače (znaky v separator poli) nejsou zahrnuty do prvků vráceného pole. Pokud například separator pole obsahuje znak "-" a hodnota aktuální instance řetězce je "aa-bb-cc", vrátí metoda pole, které obsahuje tři prvky: "aa", "bb" a "cc".
Pokud tato instance neobsahuje žádné znaky v separator, vrácená matice se skládá z jednoho prvku, který obsahuje tuto instanci.
options Pokud je RemoveEmptyEntries parametr a délka této instance je nula, metoda vrátí prázdné pole.
Každý prvek separator definuje samostatný oddělovač, který se skládá z jednoho znaku.
options Pokud argument je Nonea dva oddělovače jsou sousední nebo oddělovač je nalezen na začátku nebo na konci této instance, odpovídající prvek pole obsahuje String.Empty. Pokud například separator obsahuje dva prvky a '_''-' hodnota instance řetězce je -_aa-_, a hodnota argumentu options je None, metoda vrátí pole řetězce s následujícími pěti prvky:
String.Empty, který představuje prázdný řetězec, který předchází znaku "-" v indexu 0.
String.Empty, který představuje prázdný řetězec mezi znakem "-" v indexu 0 a znakem "_" v indexu 1.
"aa".
String.Empty, který představuje prázdný řetězec, který následuje za znakem "-" v indexu 4.
String.Empty, který představuje prázdný řetězec, který následuje za znakem "_" v indexu 5.
Pole oddělovače
separator Pokud je null parametr nebo neobsahuje žádné znaky, předpokládá se, že prázdné znaky jsou oddělovači. Prázdné znaky jsou definovány standardem Unicode a Char.IsWhiteSpace metoda vrátí true , pokud jsou předány do něj.
Chcete-li předat null parametr char[] separator , je nutné určit typ null , který má zrušit nejednoznačnost volání z některých jiných přetížení, například Split(String[], StringSplitOptions). Následující příklad ukazuje několik způsobů, jak jednoznačně identifikovat toto přetížení.
string phrase = "The quick brown fox";
_ = phrase.Split(default(char[]), StringSplitOptions.RemoveEmptyEntries);
_ = phrase.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries);
_ = phrase.Split(null as char[], StringSplitOptions.RemoveEmptyEntries);
let phrase = "The quick brown fox"
phrase.Split(Unchecked.defaultof<char[]>, StringSplitOptions.RemoveEmptyEntries) |> ignore
phrase.Split(null :> char[], StringSplitOptions.RemoveEmptyEntries) |> ignore
phrase.Split((null: char[]), StringSplitOptions.RemoveEmptyEntries) |> ignore
Dim phrase As String = "The quick brown fox"
Dim words() As String
words = phrase.Split(TryCast(Nothing, Char()),
StringSplitOptions.RemoveEmptyEntries)
words = phrase.Split(New Char() {},
StringSplitOptions.RemoveEmptyEntries)
Podrobnosti porovnání
Metoda Split extrahuje podřetězce v tomto řetězci, které jsou oddělené jedním nebo více znaky v parametru separator , a vrátí tyto podřetězce jako prvky pole.
Metoda Split hledá oddělovače provedením porovnání pomocí pravidel řazení s rozlišováním malých a velkých písmen. Další informace o slovech, řetězcích a řadových řazeních najdete ve výčtu System.Globalization.CompareOptions .
Důležité informace o výkonu
Metody Split přidělují paměť pro vrácený maticový objekt a String objekt pro každý prvek pole. Pokud vaše aplikace vyžaduje optimální výkon nebo pokud je správa přidělení paměti ve vaší aplikaci důležitá, zvažte použití IndexOf metody nebo IndexOfAny metody a volitelně Compare vyhledejte podřetězce v řetězci.
Pokud rozdělujete řetězec na znak oddělovače, pomocí IndexOf nebo IndexOfAny metody vyhledejte v řetězci znak oddělovače. Pokud rozdělujete řetězec na řetězec oddělovače, použijte IndexOf metodu nebo IndexOfAny vyhledejte první znak řetězce oddělovače. Pak pomocí Compare metody určete, zda se znaky za tímto prvním znakem rovnají zbývajícím znakům řetězce oddělovače.
Kromě toho platí, že pokud se ke rozdělení řetězců ve více Split voláních metod používá stejná sada znaků, zvažte vytvoření jednoho pole a odkazování na ni v každém volání metody. Tím se výrazně sníží režijní náklady na každé volání metody.
Poznámky pro volající
V rozhraní .NET Framework 3.5 a starších verzích, pokud Split(Char[]) je metoda předána separator nebo null neobsahuje žádné znaky, metoda používá mírně odlišnou sadu prázdných znaků k rozdělení řetězce, než Trim(Char[]) metoda provádí oříznutí řetězce. Počínaje rozhraním .NET Framework 4 používají obě metody stejnou sadu prázdných znaků Unicode.
Platí pro
Split(Char[], Int32)
- Zdroj:
- String.Manipulation.cs
- Zdroj:
- String.Manipulation.cs
- Zdroj:
- String.Manipulation.cs
- Zdroj:
- String.Manipulation.cs
Rozdělí řetězec na maximální počet podřetězců na základě zadaných znaků s oddělovači.
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()
Parametry
- separator
- Char[]
Pole znaků, které odděluje podřetězce v tomto řetězci, prázdné pole, které neobsahuje žádné oddělovače nebo null.
- count
- Int32
Maximální počet podřetěžců, které se mají vrátit.
Návraty
Matice, jejíž prvky obsahují podřetětěce v této instanci, které jsou odděleny jedním nebo více znaky v separator. Další informace najdete v části Poznámky.
Výjimky
count je negativní.
Příklady
Následující příklad ukazuje, jak count lze použít k omezení počtu řetězců vrácených Split.
string name = "Alex Johnson III";
string[] subs = name.Split(null, 2);
string firstName = subs[0];
string lastName;
if (subs.Length > 1)
{
lastName = subs[1];
}
// firstName = "Alex"
// lastName = "Johnson III"
let name = "Alex Johnson III"
let subs = name.Split(null, 2)
let firstName = subs[0]
let lastName =
if subs.Length > 1 then
subs[1]
else
""
// firstName = "Alex"
// lastName = "Johnson III"
Console.WriteLine("What is your name?")
Dim name As String = Console.ReadLine()
Dim substrings = name.Split(" "c, count:=2)
Dim firstName As String = substrings(0)
Dim lastName As String
If substrings.Length > 1 Then
lastName = substrings(1)
End If
Console.WriteLine("firstName = ""{0}""", firstName)
Console.WriteLine("lastName = ""{0}""", lastName)
' If the user enters "Alex Johnson III":
' firstName = "Alex"
' lastName = "Johnson III"
Poznámky
Znaky oddělovače nejsou zahrnuty do prvků vráceného pole.
Pokud tato instance neobsahuje žádné znaky v separator, vrácená matice se skládá z jednoho prvku, který obsahuje tuto instanci. Pokud count je nula, vrátí se prázdné pole.
separator Pokud je null parametr nebo neobsahuje žádné znaky, předpokládá se, že prázdné znaky jsou oddělovači. Prázdné znaky jsou definovány standardem Unicode a Char.IsWhiteSpace metoda vrátí true , pokud jsou předány do něj.
Každý prvek separator definuje samostatný znak oddělovače. Pokud jsou dva oddělovače sousední nebo oddělovač je nalezen na začátku nebo na konci této instance, odpovídající prvek pole obsahuje Empty.
Pokud je v této instanci více než count podřetědců, vrátí se první count - 1 podřetěžce v prvních count - 1 prvcích návratové hodnoty a zbývající znaky v této instanci se vrátí v posledním prvku návratové hodnoty.
Pokud count je větší než počet podřetětců, vrátí se dostupné podřetětězení a nevyvolá se žádná výjimka.
Následující tabulka uvádí několik příkladů.
| Jazyk | Řetězcová hodnota | Oddělovač | Vrácená matice |
|---|---|---|---|
| jazyk C# | "42, 12, 19" | new Char[] {',', ' '} | {"42", "", "12", "", "19"} |
| Visual Basic | "42, 12, 19" | Char() = {","c; " "c}) | {"42", "", "12", "", "19"} |
| jazyk C# | "42..12..19." | new Char[] {'.'} | {"42", "", "12", "", "19", ""} |
| Visual Basic | "42..12..19." | Char() = {"." c} | {"42", "", "12", "", "19", ""} |
| jazyk C# | "Banán" | new Char[] {'.'} | {"Banán"} |
| Visual Basic | "Banán" | Char() = {"." c} | {"Banán"} |
| jazyk C# | "Darb\nSmarba" | nový znak[] {} | {"Darb", "Smarba"} |
| Visual Basic | "Darb" & vbLf & "Smarba" | Char() = {} | {"Darb", "Smarba"} |
| jazyk C# | "Darb\nSmarba" | null | {"Darb", "Smarba"} |
| Visual Basic | "Darb" & vbLf & "Smarba" | Nic | {"Darb", "Smarba"} |
Důležité informace o výkonu
Metody Split přidělují paměť pro vrácený maticový objekt a String objekt pro každý prvek pole. Pokud vaše aplikace vyžaduje optimální výkon nebo pokud je správa přidělení paměti ve vaší aplikaci důležitá, zvažte použití IndexOf metody nebo IndexOfAny metody a volitelně Compare vyhledejte podřetězce v řetězci.
Pokud rozdělujete řetězec na znak oddělovače, pomocí IndexOf nebo IndexOfAny metody vyhledejte v řetězci znak oddělovače. Pokud rozdělujete řetězec na řetězec oddělovače, použijte IndexOf metodu nebo IndexOfAny vyhledejte první znak řetězce oddělovače. Pak pomocí Compare metody určete, zda se znaky za tímto prvním znakem rovnají zbývajícím znakům řetězce oddělovače.
Kromě toho platí, že pokud se ke rozdělení řetězců ve více Split voláních metod používá stejná sada znaků, zvažte vytvoření jednoho pole a odkazování na ni v každém volání metody. Tím se výrazně sníží režijní náklady na každé volání metody.
Poznámky pro volající
V rozhraní .NET Framework 3.5 a starších verzích, pokud Split(Char[]) je metoda předána separator nebo null neobsahuje žádné znaky, metoda používá mírně odlišnou sadu prázdných znaků k rozdělení řetězce, než Trim(Char[]) metoda provádí oříznutí řetězce. Počínaje rozhraním .NET Framework 4 používají obě metody stejnou sadu prázdných znaků Unicode.
Viz také
- Char
- Array
- Int32
- Concat(Object)
- Insert(Int32, String)
- Join(String, String[])
- Remove(Int32, Int32)
- Replace(Char, Char)
- Substring(Int32)
- Trim(Char[])
Platí pro
Split(Char, StringSplitOptions)
- Zdroj:
- String.Manipulation.cs
- Zdroj:
- String.Manipulation.cs
- Zdroj:
- String.Manipulation.cs
- Zdroj:
- String.Manipulation.cs
Rozdělí řetězec na podřetězce na základě zadaného znaku oddělovače a volitelně i možností.
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()
Parametry
- separator
- Char
Znak, který odděluje podřetězce v tomto řetězci.
- options
- StringSplitOptions
Bitové kombinace hodnot výčtu, která určuje, zda se mají oříznout podřetězce a zahrnout prázdné podřetězce.
Návraty
Matice, jejíž prvky obsahují podřetětěce z této instance, které jsou odděleny .separator
Platí pro
Split(ReadOnlySpan<Char>)
- Zdroj:
- String.Manipulation.cs
Rozdělí řetězec na podřetězce na základě zadaných znaků s oddělovači.
public:
cli::array <System::String ^> ^ Split(ReadOnlySpan<char> separator);
public string[] Split(scoped ReadOnlySpan<char> separator);
member this.Split : ReadOnlySpan<char> -> string[]
Public Function Split (separator As ReadOnlySpan(Of Char)) As String()
Parametry
- separator
- ReadOnlySpan<Char>
Rozsah oddělovačů nebo prázdné rozpětí, které neobsahuje žádné oddělovače.
Návraty
Matice, jejíž prvky obsahují podřetětěce z této instance, které jsou odděleny jedním nebo více znaky v separator.
Platí pro
Split(Char[])
- Zdroj:
- String.Manipulation.cs
- Zdroj:
- String.Manipulation.cs
- Zdroj:
- String.Manipulation.cs
- Zdroj:
- String.Manipulation.cs
Rozdělí řetězec na podřetězce na základě zadaných znaků s oddělovači.
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()
Parametry
- separator
- Char[]
Pole oddělovacích znaků, prázdné pole, které neobsahuje žádné oddělovače nebo null.
Návraty
Matice, jejíž prvky obsahují podřetětěce z této instance, které jsou odděleny jedním nebo více znaky v separator. Další informace najdete v části Poznámky.
Příklady
Následující příklad ukazuje, jak extrahovat jednotlivá slova z bloku textu tím, že zachází se znakem mezery ( ) a znakem tabulátoru (\t) jako oddělovači. Řetězec, který se rozděluje, obsahuje oba tyto znaky.
string s = "Today\tI'm going to school";
string[] subs = s.Split(' ', '\t');
foreach (var sub in subs)
{
Console.WriteLine($"Substring: {sub}");
}
// This example produces the following output:
//
// Substring: Today
// Substring: I'm
// Substring: going
// Substring: to
// Substring: school
let s = "Today\tI'm going to school"
let subs = s.Split(' ', '\t')
for sub in subs do
printfn $"Substring: {sub}"
// This example produces the following output:
//
// Substring: Today
// Substring: I'm
// Substring: going
// Substring: to
// Substring: school
Dim s As String = "Today" & vbTab & "I'm going to school"
Dim subs As String() = s.Split(" "c, Char.Parse(vbTab))
For Each substring In subs
Console.WriteLine("Substring: " & substring)
Next
' This example produces the following output:
'
' Substring: Today
' Substring: I 'm
' Substring: going
' Substring: to
' Substring: school
Poznámky
Pokud je řetězec oddělený známou sadou znaků, můžete ji použít Split(Char[]) k jeho oddělení do podřetězců.
Znaky oddělovače nejsou zahrnuty do prvků vráceného pole. Pokud například oddělovač obsahuje znak "-" a hodnota aktuální instance řetězce je "aa-bb-cc", vrátí metoda pole, které obsahuje tři prvky: "aa", "bb" a "cc".
Pokud tato instance neobsahuje žádné znaky v separator, vrácená matice se skládá z jednoho prvku, který obsahuje tuto instanci.
Každý prvek separator definuje samostatný znak oddělovače. Jsou-li dva oddělovače sousední nebo oddělovač je nalezen na začátku nebo na konci této instance, odpovídající prvek ve vrácené matici obsahuje Empty.
Následující tabulka uvádí několik příkladů.
| Jazyk | Řetězcová hodnota | Oddělovač | Vrácená matice |
|---|---|---|---|
| jazyk C# | "42, 12, 19" | new Char[] {',', ' '} | {"42", "", "12", "", "19"} |
| Visual Basic | "42, 12, 19" | Char() = {","c; " "c}) | {"42", "", "12", "", "19"} |
| jazyk C# | "42..12..19." | new Char[] {'.'} | {"42", "", "12", "", "19", ""} |
| Visual Basic | "42..12..19." | Char() = {"." c} | {"42", "", "12", "", "19", ""} |
| jazyk C# | "Banán" | new Char[] {'.'} | {"Banán"} |
| Visual Basic | "Banán" | Char() = {"." c} | {"Banán"} |
| jazyk C# | "Darb\nSmarba" | nový znak[] {} | {"Darb", "Smarba"} |
| Visual Basic | "Darb" & vbLf & "Smarba" | Char() = {} | {"Darb", "Smarba"} |
| jazyk C# | "Darb\nSmarba" | null | {"Darb", "Smarba"} |
| Visual Basic | "Darb" & vbLf & "Smarba" | Nic | {"Darb", "Smarba"} |
Pole oddělovače
Každý prvek oddělovače definuje samostatný oddělovač, který se skládá z jednoho znaku.
separator Pokud argument je null nebo neobsahuje žádné znaky, metoda považuje prázdné znaky za oddělovače. Prázdné znaky jsou definovány standardem Unicode a Char.IsWhiteSpace metoda vrátí true , pokud je do něj předán prázdný znak.
String.Split(Char[]) a překlad přetížení kompilátoru
I když jeden parametr pro toto přetížení String.Split je pole znaků, můžete ho volat jedním znakem, jak ukazuje následující příklad.
string value = "This is a short string.";
char delimiter = 's';
string[] substrings = value.Split(delimiter);
foreach (var substring in substrings)
Console.WriteLine(substring);
// The example displays the following output:
// Thi
// i
// a
// hort
// tring.
let value = "This is a short string."
let delimiter = 's'
let substrings = value.Split delimiter
for substring in substrings do
printfn $"{substring}"
// The example displays the following output:
// Thi
// i
// a
// hort
// tring.
Dim value As String = "This is a short string."
Dim delimiter As Char = "s"c
Dim substrings() As String = value.Split(delimiter)
For Each substring In substrings
Console.WriteLine(substring)
Next
End Sub
' The example displays the following output:
'
' Thi
' i
' a
' hort
' tring.
Vzhledem k tomu, že separator parametr je dekorován atributem ParamArrayAttribute , kompilátory interpretují jeden znak jako pole znaků s jedním prvkem. Toto není případ jiných String.Split přetížení, která obsahují separator parametr. Tyto přetížení musíte explicitně předat pole znaků jako separator argument.
Podrobnosti porovnání
Split(Char[]) Metoda extrahuje podřetězce v tomto řetězci, které jsou oddělené jedním nebo více znaky v separator poli, a vrátí tyto podřetězce jako prvky pole.
Metoda Split(Char[]) hledá oddělovače provedením porovnání pomocí pravidel řazení s rozlišováním malých a velkých písmen. Další informace o slovech, řetězcích a řadových řazeních najdete ve výčtu System.Globalization.CompareOptions .
Důležité informace o výkonu
Metody Split přidělují paměť pro vrácený maticový objekt a String objekt pro každý prvek pole. Pokud vaše aplikace vyžaduje optimální výkon nebo pokud je správa přidělení paměti ve vaší aplikaci důležitá, zvažte použití IndexOf metody nebo IndexOfAny metody. Máte také možnost použít metodu Compare k vyhledání podřetězce v řetězci.
Chcete-li rozdělit řetězec na znak oddělovače, použijte IndexOf nebo IndexOfAny metodu k vyhledání znaku oddělovače v řetězci. Chcete-li rozdělit řetězec na řetězec oddělovače, použijte IndexOf metodu nebo IndexOfAny vyhledejte první znak řetězce oddělovače. Pak pomocí Compare metody určete, zda se znaky za tímto prvním znakem rovnají zbývajícím znakům řetězce oddělovače.
Kromě toho platí, že pokud se ke rozdělení řetězců ve více Split voláních metod používá stejná sada znaků, zvažte vytvoření jednoho pole a odkazování na ni v každém volání metody. Tím se výrazně sníží režijní náklady na každé volání metody.
Poznámky pro volající
V rozhraní .NET Framework 3.5 a starších verzích, pokud Split(Char[]) je metoda předána separator nebo null neobsahuje žádné znaky, metoda používá mírně odlišnou sadu prázdných znaků k rozdělení řetězce, než Trim(Char[]) metoda provádí oříznutí řetězce. Počínaje rozhraním .NET Framework 4 používají obě metody stejnou sadu prázdných znaků Unicode.
Viz také
- Char
- Concat(Object)
- Insert(Int32, String)
- Join(String, String[])
- Remove(Int32, Int32)
- Replace(Char, Char)
- Substring(Int32)
- Trim(Char[])
Platí pro
Split(String, StringSplitOptions)
- Zdroj:
- String.Manipulation.cs
- Zdroj:
- String.Manipulation.cs
- Zdroj:
- String.Manipulation.cs
- Zdroj:
- String.Manipulation.cs
Rozdělí řetězec na podřetězce založené na zadaném oddělovači řetězců.
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()
Parametry
- separator
- String
Řetězec, který odděluje podřetězce v tomto řetězci.
- options
- StringSplitOptions
Bitové kombinace hodnot výčtu, která určuje, zda se mají oříznout podřetězce a zahrnout prázdné podřetězce.
Návraty
Matice, jejíž prvky obsahují podřetětěce z této instance, které jsou odděleny .separator