String.Split Methode
Definitie
Belangrijk
Bepaalde informatie heeft betrekking op een voorlopige productversie die aanzienlijk kan worden gewijzigd voordat deze wordt uitgebracht. Microsoft biedt geen enkele expliciete of impliciete garanties met betrekking tot de informatie die hier wordt verstrekt.
Retourneert een tekenreeksmatrix die de subtekenreeksen in dit exemplaar bevat die worden gescheiden door elementen van een opgegeven tekenreeks of Unicode-tekenmatrix.
Overloads
| Name | Description |
|---|---|
| Split(Rune, StringSplitOptions) | |
| Split(String[], Int32, StringSplitOptions) |
Splitst een tekenreeks in een maximum aantal subtekenreeksen op basis van opgegeven scheidingstekenreeksen en optioneel opties. |
| Split(Rune, Int32, StringSplitOptions) | |
| Split(Char[], Int32, StringSplitOptions) |
Splitst een tekenreeks in een maximum aantal subtekenreeksen op basis van opgegeven scheidingstekens en optioneel opties. |
| Split(Char, Int32, StringSplitOptions) |
Splitst een tekenreeks in een maximum aantal subtekenreeksen op basis van het opgegeven tekenscheidingsteken, optioneel lege subtekenreeksen weglaten uit het resultaat. |
| Split(String[], StringSplitOptions) |
Splitst een tekenreeks in subtekenreeksen op basis van een opgegeven scheidingstekenreeks en optioneel opties. |
| Split(String, Int32, StringSplitOptions) |
Splitst een tekenreeks in een maximum aantal subtekenreeksen op basis van een opgegeven scheidingstekenreeks en, optioneel, opties. |
| Split(Char[], StringSplitOptions) |
Hiermee wordt een tekenreeks gesplitst in subtekenreeksen op basis van opgegeven scheidingstekens en opties. |
| Split(Char[], Int32) |
Splitst een tekenreeks in een maximum aantal subtekenreeksen op basis van opgegeven scheidingstekens. |
| Split(Char, StringSplitOptions) |
Hiermee wordt een tekenreeks gesplitst in subtekenreeksen op basis van een opgegeven scheidingsteken en optioneel opties. |
| Split(ReadOnlySpan<Char>) |
Splitst een tekenreeks in subtekenreeksen op basis van opgegeven scheidingstekens. |
| Split(Char[]) |
Splitst een tekenreeks in subtekenreeksen op basis van opgegeven scheidingstekens. |
| Split(String, StringSplitOptions) |
Splitst een tekenreeks in subtekenreeksen die zijn gebaseerd op het opgegeven tekenreeksscheidingsteken. |
Opmerkingen
Split wordt gebruikt om een tekenreeks met scheidingstekens op te splitsen in subtekenreeksen. U kunt een tekenmatrix of een tekenreeksmatrix gebruiken om nul of meer scheidingstekens of tekenreeksen op te geven. Als er geen scheidingstekens worden opgegeven, wordt de tekenreeks gesplitst in spatietekens.
Met overbelasting van de Split methode kunt u het aantal subtekenreeksen beperken dat wordt geretourneerd door de methode (de Split(Char[], Int32) methode), om op te geven of lege tekenreeksen en/of subtekenreeksen in het resultaat moeten worden opgenomen (de Split(Char[], StringSplitOptions) en Split(String[], StringSplitOptions) methoden), of om beide te doen (de Split(Char[], Int32, StringSplitOptions) en Split(String[], Int32, StringSplitOptions) methoden).
Tip
De Split methode is niet altijd de beste manier om een gescheiden tekenreeks op te splitsen in subtekenreeksen. Als u niet alle subtekenreeksen van een gescheiden tekenreeks wilt extraheren of als u een tekenreeks wilt parseren op basis van een patroon in plaats van een set scheidingstekens, kunt u overwegen om reguliere expressies te gebruiken of een van de zoekmethoden te combineren die de index van een teken met de Substring methode retourneren. Zie Subtekenreeksen uit een tekenreeks extraheren voor meer informatie.
Voorbeeld
In de volgende voorbeelden ziet u drie verschillende overbelastingen van String.Split(). Het eerste voorbeeld roept de Split(Char[]) overbelasting aan en geeft één scheidingsteken door.
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.
Zoals u ziet, worden de punttekens (.) opgenomen in twee subtekenreeksen. Als u de punttekens wilt uitsluiten, kunt u het puntteken toevoegen als een extra scheidingsteken. In het volgende voorbeeld ziet u hoe u dit doet.
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:
De perioden zijn verdwenen uit de subtekenreeksen, maar nu zijn er twee extra lege subtekenreeksen opgenomen. Deze lege subtekenreeksen vertegenwoordigen de subtekenreeks tussen een woord en de punt die erop volgt. Als u lege subtekenreeksen uit de resulterende matrix wilt weglaten, kunt u de Split(Char[], StringSplitOptions) overbelasting aanroepen en opgeven StringSplitOptions.RemoveEmptyEntries voor de options parameter.
string s = "You win some. You lose some.";
char[] separators = new char[] { ' ', '.' };
string[] subs = s.Split(separators, StringSplitOptions.RemoveEmptyEntries);
foreach (var sub in subs)
{
Console.WriteLine($"Substring: {sub}");
}
// This example produces the following output:
//
// Substring: You
// Substring: win
// Substring: some
// Substring: You
// Substring: lose
// Substring: some
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
De secties voor de afzonderlijke overbelastingen String.Split() bevatten verdere voorbeelden.
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()
Parameters
- separator
- Rune
- options
- StringSplitOptions
Retouren
Van toepassing op
Split(String[], Int32, StringSplitOptions)
Splitst een tekenreeks in een maximum aantal subtekenreeksen op basis van opgegeven scheidingstekenreeksen en optioneel opties.
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()
Parameters
- separator
- String[]
De tekenreeksen die de subtekenreeksen in deze tekenreeks scheiden, een lege matrix die geen scheidingstekens bevat of null.
- count
- Int32
Het maximum aantal subtekenreeksen dat moet worden geretourneerd.
- options
- StringSplitOptions
Een bitsgewijze combinatie van de opsommingswaarden die aangeeft of subtekenreeksen moeten worden ingekort en lege subtekenreeksen moeten worden opgenomen.
Retouren
Een matrix waarvan de elementen de subtekenreeksen in deze tekenreeks bevatten die worden gescheiden door een of meer tekenreeksen in separator. Zie de sectie Opmerkingen voor meer informatie.
- Kenmerken
Uitzonderingen
count is negatief.
options is geen van de StringSplitOptions waarden.
Voorbeelden
In het volgende voorbeeld wordt de StringSplitOptions opsomming gebruikt om subtekenreeksen op te nemen of uit te sluiten die door de Split methode zijn gegenereerd.
// 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]>
'
Opmerkingen
Scheidingstekenreeksen worden niet opgenomen in de elementen van de geretourneerde matrix.
Als dit exemplaar geen tekenreeksen bevat of separatorals de count parameter 1 is, bestaat de geretourneerde matrix uit één element dat dit exemplaar bevat.
Als de separator parameter tekens bevat of geen tekens bevat null , wordt ervan uitgegaan dat spatietekens de scheidingstekens zijn. Spatietekens worden gedefinieerd door de Unicode-standaard en de Char.IsWhiteSpace methode retourneert true als ze eraan worden doorgegeven.
Als u wilt doorgeven null voor de string[] separator parameter, moet u het type van de null aanroep aangeven dat de aanroep van een aantal andere overbelastingen, zoals Split(Char[], Int32, StringSplitOptions). In het volgende voorbeeld ziet u verschillende manieren om deze overbelasting ondubbelzinnig te identificeren.
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)
Als de count parameter nul is of als de options parameter RemoveEmptyEntries en de lengte van dit exemplaar nul is, wordt een lege matrix geretourneerd.
Elk element van het definiëren van separator een afzonderlijk scheidingsteken dat uit een of meer tekens bestaat. Als de options parameter is Noneen er twee scheidingstekens naast elkaar staan of als er aan het begin of einde van dit exemplaar een scheidingsteken wordt gevonden, bevat Emptyhet bijbehorende matrixelement .
Als er meer dan count subtekenreeksen in dit exemplaar zijn, worden de eerste count min 1 subtekenreeksen geretourneerd in de eerste count min 1 elementen van de retourwaarde en worden de resterende tekens in dit exemplaar geretourneerd in het laatste element van de retourwaarde.
Als count deze groter is dan het aantal subtekenreeksen, worden de beschikbare subtekenreeksen geretourneerd en wordt er geen uitzondering gegenereerd.
De scheidingstekenmatrix
Als een van de elementen uit separator meerdere tekens bestaat, wordt de hele subtekenreeks beschouwd als een scheidingsteken. Als een van de elementen in separator bijvoorbeeld '10' is, wordt geprobeerd de tekenreeks 'This10is10a10string' te splitsen. Retourneert deze matrix met vier elementen: { "This", "is", "a", "string." }.
Vergelijkingsdetails
De Split methode extraheert de subtekenreeksen in deze tekenreeks die worden gescheiden door een of meer tekenreeksen in de separator parameter en retourneert deze subtekenreeksen als elementen van een matrix.
De Split methode zoekt naar scheidingstekens door vergelijkingen uit te voeren met hoofdlettergevoelige ordinale sorteerregels. Zie de System.Globalization.CompareOptions opsomming voor meer informatie over woorden, tekenreeksen en rangschikkingen.
De Split methode negeert een element van separator wie de waarde is null of de lege tekenreeks ("").
Om dubbelzinnige resultaten te voorkomen wanneer tekenreeksen separator gemeenschappelijk tekens bevatten, gaat de Split methode van het begin tot het einde van de waarde van het exemplaar en komt overeen met het eerste element in separator dat gelijk is aan een scheidingsteken in het exemplaar. De volgorde waarin subtekenreeksen in het exemplaar worden aangetroffen, heeft voorrang op de volgorde van elementen in separator.
Denk bijvoorbeeld aan een exemplaar waarvan de waarde 'abcdef' is. Als het eerste element separator 'ef' was en het tweede element 'bcde' was, zou het resultaat van de splitsbewerking 'a' en 'f' zijn. Dit komt doordat de subtekenreeks in het exemplaar bcde wordt aangetroffen en overeenkomt met een element voordat separator de subtekenreeks 'f' wordt aangetroffen.
Als het eerste element separator echter 'bcd' was en het tweede element 'bc' was, zou het resultaat van de splitsbewerking 'a' en 'ef' zijn. Dit komt doordat bcd het eerste scheidingsteken is dat separator overeenkomt met een scheidingsteken in het exemplaar. Als de volgorde van de scheidingstekens werd omgekeerd zodat het eerste element 'bc' was en het tweede element 'bcd' was, zou het resultaat 'a' en 'def' zijn.
Prestatie-overwegingen
De Split methoden wijzen geheugen toe voor het geretourneerde matrixobject en een String object voor elk matrixelement. Als uw toepassing optimale prestaties vereist of als het beheren van geheugentoewijzing essentieel is in uw toepassing, kunt u overwegen de IndexOf of IndexOfAny methode en eventueel de Compare methode te gebruiken om een subtekenreeks in een tekenreeks te vinden.
Als u een tekenreeks splitst op een scheidingsteken, gebruikt u de IndexOf of IndexOfAny methode om een scheidingsteken in de tekenreeks te zoeken. Als u een tekenreeks splitst op een scheidingstekenreeks, gebruikt u de IndexOf of IndexOfAny methode om het eerste teken van de scheidingstekenreeks te zoeken. Gebruik vervolgens de Compare methode om te bepalen of de tekens na dat eerste teken gelijk zijn aan de resterende tekens van de scheidingstekenreeks.
Als dezelfde set tekens wordt gebruikt voor het splitsen van tekenreeksen in meerdere Split methode-aanroepen, kunt u ook één matrix maken en ernaar verwijzen in elke methode-aanroep. Dit vermindert de extra overhead van elke methode-aanroep aanzienlijk.
Notities voor bellers
Als in .NET Framework 3.5 en eerdere versies de methode Split(Char[]) wordt doorgegeven aan een separator die null of geen tekens bevat, gebruikt de methode een iets andere set witruimtetekens om de tekenreeks te splitsen dan de methode Trim(Char[]) om de tekenreeks te knippen. Vanaf .NET Framework 4 gebruiken beide methoden een identieke set Unicode-spatietekens.
Van toepassing op
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()
Parameters
- separator
- Rune
- count
- Int32
- options
- StringSplitOptions
Retouren
Van toepassing op
Split(Char[], Int32, StringSplitOptions)
Splitst een tekenreeks in een maximum aantal subtekenreeksen op basis van opgegeven scheidingstekens en optioneel opties.
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()
Parameters
- separator
- Char[]
Een matrix met tekens die de subtekenreeksen in deze tekenreeks scheiden, een lege matrix die geen scheidingstekens bevat of null.
- count
- Int32
Het maximum aantal subtekenreeksen dat moet worden geretourneerd.
- options
- StringSplitOptions
Een bitsgewijze combinatie van de opsommingswaarden die aangeeft of subtekenreeksen moeten worden ingekort en lege subtekenreeksen moeten worden opgenomen.
Retouren
Een matrix die de subtekenreeksen in deze tekenreeks bevat die worden gescheiden door een of meer tekens in separator. Zie de sectie Opmerkingen voor meer informatie.
- Kenmerken
Uitzonderingen
count is negatief.
options is geen van de StringSplitOptions waarden.
Voorbeelden
In het volgende voorbeeld wordt de StringSplitOptions opsomming gebruikt om subtekenreeksen op te nemen of uit te sluiten die door de Split methode zijn gegenereerd.
// 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]>
'
Opmerkingen
Scheidingstekens worden niet opgenomen in de elementen van de geretourneerde matrix.
Als dit exemplaar geen tekens bevat in separatorof de count parameter 1 is, bestaat de geretourneerde matrix uit één element dat dit exemplaar bevat.
Als de separator parameter tekens bevat of geen tekens bevat null , wordt ervan uitgegaan dat spatietekens de scheidingstekens zijn. Spatietekens worden gedefinieerd door de Unicode-standaard en de Char.IsWhiteSpace methode retourneert true als ze eraan worden doorgegeven.
Als u wilt doorgeven null voor de char[] separator parameter, moet u het type van de null aanroep aangeven dat de aanroep van een aantal andere overbelastingen, zoals Split(String[], Int32, StringSplitOptions). In het volgende voorbeeld ziet u verschillende manieren om deze overbelasting ondubbelzinnig te identificeren.
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)
Als de count parameter nul is of als de options parameter RemoveEmptyEntries en de lengte van dit exemplaar nul is, wordt een lege matrix geretourneerd.
Elk element van het definiëren van separator een afzonderlijk scheidingsteken. Als de options parameter is Noneen er twee scheidingstekens naast elkaar staan of als er aan het begin of einde van dit exemplaar een scheidingsteken wordt gevonden, bevat Emptyhet bijbehorende matrixelement .
Als er meer dan count subtekenreeksen in dit exemplaar zijn, worden de eerste count min 1 subtekenreeksen geretourneerd in de eerste count min 1 elementen van de retourwaarde en worden de resterende tekens in dit exemplaar geretourneerd in het laatste element van de retourwaarde.
Als count deze groter is dan het aantal subtekenreeksen, worden de beschikbare subtekenreeksen geretourneerd en wordt er geen uitzondering gegenereerd.
Prestatie-overwegingen
De Split methoden wijzen geheugen toe voor het geretourneerde matrixobject en een String object voor elk matrixelement. Als uw toepassing optimale prestaties vereist of als het beheren van geheugentoewijzing essentieel is in uw toepassing, kunt u overwegen de IndexOf of IndexOfAny methode en eventueel de Compare methode te gebruiken om een subtekenreeks in een tekenreeks te vinden.
Als u een tekenreeks splitst op een scheidingsteken, gebruikt u de IndexOf of IndexOfAny methode om een scheidingsteken in de tekenreeks te zoeken. Als u een tekenreeks splitst op een scheidingstekenreeks, gebruikt u de IndexOf of IndexOfAny methode om het eerste teken van de scheidingstekenreeks te zoeken. Gebruik vervolgens de Compare methode om te bepalen of de tekens na dat eerste teken gelijk zijn aan de resterende tekens van de scheidingstekenreeks.
Als dezelfde set tekens wordt gebruikt voor het splitsen van tekenreeksen in meerdere Split methode-aanroepen, kunt u ook één matrix maken en ernaar verwijzen in elke methode-aanroep. Dit vermindert de extra overhead van elke methode-aanroep aanzienlijk.
Notities voor bellers
Als in .NET Framework 3.5 en eerdere versies de methode Split(Char[]) wordt doorgegeven aan een separator die null of geen tekens bevat, gebruikt de methode een iets andere set witruimtetekens om de tekenreeks te splitsen dan de methode Trim(Char[]) om de tekenreeks te knippen. Vanaf .NET Framework 4 gebruiken beide methoden een identieke set Unicode-spatietekens.
Van toepassing op
Split(Char, Int32, StringSplitOptions)
Splitst een tekenreeks in een maximum aantal subtekenreeksen op basis van het opgegeven tekenscheidingsteken, optioneel lege subtekenreeksen weglaten uit het resultaat.
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()
Parameters
- separator
- Char
Een teken waarmee de subtekenreeksen in dit exemplaar worden gescheiden.
- count
- Int32
Het maximum aantal elementen dat in de matrix wordt verwacht.
- options
- StringSplitOptions
Een bitsgewijze combinatie van de opsommingswaarden die aangeeft of subtekenreeksen moeten worden ingekort en lege subtekenreeksen moeten worden opgenomen.
Retouren
Een matrix die maximaal count subtekenreeksen van dit exemplaar bevat die worden gescheiden door separator.
Opmerkingen
Als de tekenreeks al is gesplitst count - 1 keer, maar het einde van de tekenreeks niet is bereikt, bevat de laatste tekenreeks in de geretourneerde matrix de resterende subtekenreeks van dit exemplaar, ongewijzigd.
Van toepassing op
Split(String[], StringSplitOptions)
Splitst een tekenreeks in subtekenreeksen op basis van een opgegeven scheidingstekenreeks en optioneel opties.
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()
Parameters
- separator
- String[]
Een matrix met tekenreeksen die de subtekenreeksen in deze tekenreeks scheiden, een lege matrix die geen scheidingstekens bevat of null.
- options
- StringSplitOptions
Een bitsgewijze combinatie van de opsommingswaarden die aangeeft of subtekenreeksen moeten worden ingekort en lege subtekenreeksen moeten worden opgenomen.
Retouren
Een matrix waarvan de elementen de subtekenreeksen in deze tekenreeks bevatten die worden gescheiden door een of meer tekenreeksen in separator. Zie de sectie Opmerkingen voor meer informatie.
- Kenmerken
Uitzonderingen
options is geen van de StringSplitOptions waarden.
Voorbeelden
In het volgende voorbeeld ziet u het verschil in de matrices die worden geretourneerd door de methode van String.Split(String[], StringSplitOptions) een tekenreeks aan te roepen met de options parameter gelijk aan StringSplitOptions.None en 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'
In het volgende voorbeeld wordt een matrix met scheidingstekens gedefinieerd die leestekens en spatietekens bevatten. Door deze matrix samen met een waarde van StringSplitOptions.RemoveEmptyEntries de Split(String[], StringSplitOptions) methode door te geven, wordt een matrix geretourneerd die bestaat uit de afzonderlijke woorden uit de tekenreeks.
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
Houd er rekening mee dat de methode wordt aangeroepen met het options argument ingesteld op StringSplitOptions.RemoveEmptyEntries. Hiermee voorkomt u dat de geretourneerde matrix waarden opgeeft String.Empty die overeenkomen met lege subtekenreeksen tussen interpunctiemarkeringen en spatietekens.
Opmerkingen
Wanneer een tekenreeks wordt gescheiden door een bekende set tekenreeksen, kunt u de Split methode gebruiken om deze te scheiden in subtekenreeksen.
Scheidingstekenreeksen worden niet opgenomen in de elementen van de geretourneerde matrix. Als de separator matrix bijvoorbeeld de tekenreeks '--' bevat en de waarde van het huidige tekenreeksexemplaren 'aa--bb--cc' is, retourneert de methode een matrix die drie elementen bevat: 'aa', 'bb' en 'cc'.
Als dit exemplaar geen tekenreeksen separatorbevat, bestaat de geretourneerde matrix uit één element dat dit exemplaar bevat.
Als de options parameter is RemoveEmptyEntries en de lengte van dit exemplaar nul is, retourneert de methode een lege matrix.
Elk element van het definiëren van separator een afzonderlijk scheidingsteken dat uit een of meer tekens bestaat. Als het options argument is Noneen er twee scheidingstekens naast elkaar liggen of als er aan het begin of einde van dit exemplaar een scheidingsteken wordt gevonden, bevat String.Emptyhet bijbehorende matrixelement . Als separator er bijvoorbeeld twee elementen zijn, '-' en '_', is de waarde van het tekenreeksexemplaren '-_aa-_', en de waarde van het options argument is None, retourneert de methode een tekenreeksmatrix met de volgende vijf elementen:
String.Empty, die de lege tekenreeks aangeeft die voorafgaat aan de subtekenreeks '-' op index 0.
String.Empty, dat de lege tekenreeks aangeeft tussen de subtekenreeks '-' bij index 0 en de subtekenreeks '_' op index 1.
"aa".
String.Empty, die de lege tekenreeks aangeeft die de subtekenreeks '-' volgt op index 4.
String.Empty, die de lege tekenreeks aangeeft die de subtekenreeks '_' volgt op index 5.
De scheidingstekenmatrix
Als een van de elementen uit separator meerdere tekens bestaat, wordt de hele subtekenreeks beschouwd als een scheidingsteken. Als een van de elementen in separator bijvoorbeeld '10' is, wordt geprobeerd de tekenreeks 'This10is10a10string' te splitsen. Retourneert de volgende matrix met vier elementen: { "This", "is", "a", "string." }.
Als de separator parameter geen niet-lege tekenreeksen is null of bevat, worden spatietekens verondersteld de scheidingstekens te zijn. Spatietekens worden gedefinieerd door de Unicode-standaard en de Char.IsWhiteSpace methode retourneert true als ze eraan worden doorgegeven.
Als u wilt doorgeven null voor de string[] separator parameter, moet u het type van de null aanroep aangeven dat de aanroep van een aantal andere overbelastingen, zoals Split(Char[], StringSplitOptions). In het volgende voorbeeld ziet u verschillende manieren om deze overbelasting ondubbelzinnig te identificeren.
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)
Vergelijkingsdetails
De Split methode extraheert de subtekenreeksen in deze tekenreeks die worden gescheiden door een of meer tekenreeksen in de separator parameter en retourneert deze subtekenreeksen als elementen van een matrix.
De Split methode zoekt naar scheidingstekens door vergelijkingen uit te voeren met hoofdlettergevoelige ordinale sorteerregels. Zie de System.Globalization.CompareOptions opsomming voor meer informatie over woorden, tekenreeksen en rangschikkingen.
De Split methode negeert een element van separator wie de waarde is null of de lege tekenreeks ("").
Om dubbelzinnige resultaten te voorkomen wanneer tekenreeksen separator gemeenschappelijk tekens bevatten, gaat de Split bewerking van het begin tot het einde van de waarde van het exemplaar en komt overeen met het eerste element in separator dat gelijk is aan een scheidingsteken in het exemplaar. De volgorde waarin subtekenreeksen in het exemplaar worden aangetroffen, heeft voorrang op de volgorde van elementen in separator.
Denk bijvoorbeeld aan een exemplaar waarvan de waarde 'abcdef' is. Als het eerste element separator 'ef' was en het tweede element 'bcde' was, zou het resultaat van de splitsbewerking een tekenreeksmatrix zijn die twee elementen bevat, 'a' en 'f'. Dit komt doordat de subtekenreeks in het exemplaar bcde wordt aangetroffen en overeenkomt met een element voordat separator de subtekenreeks 'f' wordt aangetroffen.
Als het eerste element separator echter 'bcd' was en het tweede element 'bc' was, zou het resultaat van de splitsbewerking een tekenreeksmatrix zijn die twee elementen bevat, a en ef. Dit komt doordat bcd het eerste scheidingsteken is dat separator overeenkomt met een scheidingsteken in het exemplaar. Als de volgorde van de scheidingstekens werd omgekeerd zodat het eerste element 'bc' was en het tweede element 'bcd' was, zou het resultaat een tekenreeksmatrix zijn die twee elementen bevat, 'a' en 'def'.
Prestatie-overwegingen
De Split methoden wijzen geheugen toe voor het geretourneerde matrixobject en een String object voor elk matrixelement. Als uw toepassing optimale prestaties vereist of als het beheren van geheugentoewijzing essentieel is in uw toepassing, kunt u overwegen de IndexOf of IndexOfAny methode en eventueel de Compare methode te gebruiken om een subtekenreeks in een tekenreeks te vinden.
Als u een tekenreeks splitst op een scheidingsteken, gebruikt u de IndexOf of IndexOfAny methode om een scheidingsteken in de tekenreeks te zoeken. Als u een tekenreeks splitst op een scheidingstekenreeks, gebruikt u de IndexOf of IndexOfAny methode om het eerste teken van de scheidingstekenreeks te zoeken. Gebruik vervolgens de Compare methode om te bepalen of de tekens na dat eerste teken gelijk zijn aan de resterende tekens van de scheidingstekenreeks.
Als dezelfde set tekens wordt gebruikt voor het splitsen van tekenreeksen in meerdere Split methode-aanroepen, kunt u ook één matrix maken en ernaar verwijzen in elke methode-aanroep. Dit vermindert de extra overhead van elke methode-aanroep aanzienlijk.
Notities voor bellers
Als in .NET Framework 3.5 en eerdere versies de methode Split(Char[]) wordt doorgegeven aan een separator die null of geen tekens bevat, gebruikt de methode een iets andere set witruimtetekens om de tekenreeks te splitsen dan de methode Trim(Char[]) om de tekenreeks te knippen. Vanaf .NET Framework 4 gebruiken beide methoden een identieke set Unicode-spatietekens.
Van toepassing op
Split(String, Int32, StringSplitOptions)
Splitst een tekenreeks in een maximum aantal subtekenreeksen op basis van een opgegeven scheidingstekenreeks en, optioneel, opties.
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()
Parameters
- separator
- String
Een tekenreeks waarmee de subtekenreeksen in dit exemplaar worden gescheiden.
- count
- Int32
Het maximum aantal elementen dat in de matrix wordt verwacht.
- options
- StringSplitOptions
Een bitsgewijze combinatie van de opsommingswaarden die aangeeft of subtekenreeksen moeten worden ingekort en lege subtekenreeksen moeten worden opgenomen.
Retouren
Een matrix die maximaal count subtekenreeksen van dit exemplaar bevat die worden gescheiden door separator.
Opmerkingen
Als de tekenreeks al is gesplitst count - 1 keer, maar het einde van de tekenreeks niet is bereikt, bevat de laatste tekenreeks in de geretourneerde matrix de resterende subtekenreeks van dit exemplaar, ongewijzigd.
Van toepassing op
Split(Char[], StringSplitOptions)
Hiermee wordt een tekenreeks gesplitst in subtekenreeksen op basis van opgegeven scheidingstekens en opties.
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()
Parameters
- separator
- Char[]
Een matrix met tekens die de subtekenreeksen in deze tekenreeks scheiden, een lege matrix die geen scheidingstekens bevat of null.
- options
- StringSplitOptions
Een bitsgewijze combinatie van de opsommingswaarden die aangeeft of subtekenreeksen moeten worden ingekort en lege subtekenreeksen moeten worden opgenomen.
Retouren
Een matrix waarvan de elementen de subtekenreeksen in deze tekenreeks bevatten die worden gescheiden door een of meer tekens in separator. Zie de sectie Opmerkingen voor meer informatie.
- Kenmerken
Uitzonderingen
options is geen van de StringSplitOptions waarden.
Voorbeelden
In het volgende voorbeeld wordt de StringSplitOptions opsomming gebruikt om subtekenreeksen op te nemen of uit te sluiten die door de Split methode zijn gegenereerd.
// 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]>
'
Opmerkingen
Scheidingstekens (de tekens in de separator matrix) worden niet opgenomen in de elementen van de geretourneerde matrix. Als de separator matrix bijvoorbeeld het teken '-' bevat en de waarde van het huidige tekenreeksexemplaren 'aa-bb-cc' is, retourneert de methode een matrix die drie elementen bevat: 'aa', 'bb' en 'cc'.
Als dit exemplaar geen tekens separatorbevat, bestaat de geretourneerde matrix uit één element dat dit exemplaar bevat.
Als de options parameter is RemoveEmptyEntries en de lengte van dit exemplaar nul is, retourneert de methode een lege matrix.
Elk element van separator het definieert een afzonderlijk scheidingsteken dat uit één teken bestaat. Als het options argument is Noneen er twee scheidingstekens naast elkaar liggen of als er aan het begin of einde van dit exemplaar een scheidingsteken wordt gevonden, bevat String.Emptyhet bijbehorende matrixelement . Als separator er bijvoorbeeld twee elementen '-' zijn opgenomen en '_'de waarde van het tekenreeksexemplaren '-_aa-_' is en de waarde van het options argument is None, retourneert de methode een tekenreeksmatrix met de volgende vijf elementen:
String.Empty, die de lege tekenreeks aangeeft die voorafgaat aan het teken '-' bij index 0.
String.Empty, die de lege tekenreeks aangeeft tussen het teken '-' bij index 0 en het '_'-teken op index 1.
"aa".
String.Empty, die de lege tekenreeks aangeeft die het teken '-' volgt op index 4.
String.Empty, die de lege tekenreeks aangeeft die volgt op het teken _bij index 5.
De scheidingstekenmatrix
Als de separator parameter tekens bevat of geen tekens bevat null , wordt ervan uitgegaan dat spatietekens de scheidingstekens zijn. Spatietekens worden gedefinieerd door de Unicode-standaard en de Char.IsWhiteSpace methode retourneert true als ze eraan worden doorgegeven.
Als u wilt doorgeven null voor de char[] separator parameter, moet u het type van de null aanroep aangeven dat de aanroep van een aantal andere overbelastingen, zoals Split(String[], StringSplitOptions). In het volgende voorbeeld ziet u verschillende manieren om deze overbelasting ondubbelzinnig te identificeren.
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)
Vergelijkingsdetails
De Split methode extraheert de subtekenreeksen in deze tekenreeks die worden gescheiden door een of meer tekens in de separator parameter en retourneert deze subtekenreeksen als elementen van een matrix.
De Split methode zoekt naar scheidingstekens door vergelijkingen uit te voeren met hoofdlettergevoelige ordinale sorteerregels. Zie de System.Globalization.CompareOptions opsomming voor meer informatie over woorden, tekenreeksen en rangschikkingen.
Prestatie-overwegingen
De Split methoden wijzen geheugen toe voor het geretourneerde matrixobject en een String object voor elk matrixelement. Als uw toepassing optimale prestaties vereist of als het beheren van geheugentoewijzing essentieel is in uw toepassing, kunt u overwegen de IndexOf of IndexOfAny methode en eventueel de Compare methode te gebruiken om een subtekenreeks in een tekenreeks te vinden.
Als u een tekenreeks splitst op een scheidingsteken, gebruikt u de IndexOf of IndexOfAny methode om een scheidingsteken in de tekenreeks te zoeken. Als u een tekenreeks splitst op een scheidingstekenreeks, gebruikt u de IndexOf of IndexOfAny methode om het eerste teken van de scheidingstekenreeks te zoeken. Gebruik vervolgens de Compare methode om te bepalen of de tekens na dat eerste teken gelijk zijn aan de resterende tekens van de scheidingstekenreeks.
Als dezelfde set tekens wordt gebruikt voor het splitsen van tekenreeksen in meerdere Split methode-aanroepen, kunt u ook één matrix maken en ernaar verwijzen in elke methode-aanroep. Dit vermindert de extra overhead van elke methode-aanroep aanzienlijk.
Notities voor bellers
Als in .NET Framework 3.5 en eerdere versies de methode Split(Char[]) wordt doorgegeven aan een separator die null of geen tekens bevat, gebruikt de methode een iets andere set witruimtetekens om de tekenreeks te splitsen dan de methode Trim(Char[]) om de tekenreeks te knippen. Vanaf .NET Framework 4 gebruiken beide methoden een identieke set Unicode-spatietekens.
Van toepassing op
Split(Char[], Int32)
Splitst een tekenreeks in een maximum aantal subtekenreeksen op basis van opgegeven scheidingstekens.
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()
Parameters
- separator
- Char[]
Een matrix met tekens die de subtekenreeksen in deze tekenreeks scheiden, een lege matrix die geen scheidingstekens bevat of null.
- count
- Int32
Het maximum aantal subtekenreeksen dat moet worden geretourneerd.
Retouren
Een matrix waarvan de elementen de subtekenreeksen in dit exemplaar bevatten die worden gescheiden door een of meer tekens in separator. Zie de sectie Opmerkingen voor meer informatie.
Uitzonderingen
count is negatief.
Voorbeelden
In het volgende voorbeeld ziet u hoe count u kunt gebruiken om het aantal tekenreeksen te beperken dat wordt geretourneerd door 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"
Opmerkingen
Scheidingstekens worden niet opgenomen in de elementen van de geretourneerde matrix.
Als dit exemplaar geen tekens separatorbevat, bestaat de geretourneerde matrix uit één element dat dit exemplaar bevat. Als count nul is, wordt een lege matrix geretourneerd.
Als de separator parameter tekens bevat of geen tekens bevat null , wordt ervan uitgegaan dat spatietekens de scheidingstekens zijn. Spatietekens worden gedefinieerd door de Unicode-standaard en de Char.IsWhiteSpace methode retourneert true als ze eraan worden doorgegeven.
Elk element van het definiëren van separator een afzonderlijk scheidingsteken. Als er twee scheidingstekens naast elkaar liggen of als er aan het begin of einde van dit exemplaar een scheidingsteken wordt gevonden, bevat Emptyhet bijbehorende matrixelement .
Als er meer dan count subtekenreeksen in dit exemplaar zijn, worden de eerste subtekenreeksen geretourneerd in de eerste count - 1count - 1 elementen van de retourwaarde en worden de resterende tekens in dit exemplaar geretourneerd in het laatste element van de retourwaarde.
Als count deze groter is dan het aantal subtekenreeksen, worden de beschikbare subtekenreeksen geretourneerd en wordt er geen uitzondering gegenereerd.
In de volgende tabel ziet u enkele voorbeelden.
| Taal | Stringwaarde | Afscheider | Geretourneerde matrix |
|---|---|---|---|
| C# | "42, 12, 19" | new Char[] {',', ' '} | {"42", "", "12", "", "19"} |
| Visual Basic | "42, 12, 19" | Char() = {","c, " "c}) | {"42", "", "12", "", "19"} |
| C# | "42..12..19." | nieuw teken[] {'.'} | {"42", "", "12", "", "19", ""} |
| Visual Basic | "42..12..19." | Char() = {"." c} | {"42", "", "12", "", "19", ""} |
| C# | "Banaan" | nieuw teken[] {'.'} | {"Banaan"} |
| Visual Basic | "Banaan" | Char() = {"." c} | {"Banaan"} |
| C# | "Darb\nSmarba" | nieuw teken[] {} | {"Darb", "Smarba"} |
| Visual Basic | "Darb" & vbLf & "Smarba" | Char() = {} | {"Darb", "Smarba"} |
| C# | "Darb\nSmarba" | nul | {"Darb", "Smarba"} |
| Visual Basic | "Darb" & vbLf & "Smarba" | Niets | {"Darb", "Smarba"} |
Prestatie-overwegingen
De Split methoden wijzen geheugen toe voor het geretourneerde matrixobject en een String object voor elk matrixelement. Als uw toepassing optimale prestaties vereist of als het beheren van geheugentoewijzing essentieel is in uw toepassing, kunt u overwegen de IndexOf of IndexOfAny methode en eventueel de Compare methode te gebruiken om een subtekenreeks in een tekenreeks te vinden.
Als u een tekenreeks splitst op een scheidingsteken, gebruikt u de IndexOf of IndexOfAny methode om een scheidingsteken in de tekenreeks te zoeken. Als u een tekenreeks splitst op een scheidingstekenreeks, gebruikt u de IndexOf of IndexOfAny methode om het eerste teken van de scheidingstekenreeks te zoeken. Gebruik vervolgens de Compare methode om te bepalen of de tekens na dat eerste teken gelijk zijn aan de resterende tekens van de scheidingstekenreeks.
Als dezelfde set tekens wordt gebruikt voor het splitsen van tekenreeksen in meerdere Split methode-aanroepen, kunt u ook één matrix maken en ernaar verwijzen in elke methode-aanroep. Dit vermindert de extra overhead van elke methode-aanroep aanzienlijk.
Notities voor bellers
Als in .NET Framework 3.5 en eerdere versies de methode Split(Char[]) wordt doorgegeven aan een separator die null of geen tekens bevat, gebruikt de methode een iets andere set witruimtetekens om de tekenreeks te splitsen dan de methode Trim(Char[]) om de tekenreeks te knippen. Vanaf .NET Framework 4 gebruiken beide methoden een identieke set Unicode-spatietekens.
Zie ook
- Char
- Array
- Int32
- Concat(Object)
- Insert(Int32, String)
- Join(String, String[])
- Remove(Int32, Int32)
- Replace(Char, Char)
- Substring(Int32)
- Trim(Char[])
Van toepassing op
Split(Char, StringSplitOptions)
Hiermee wordt een tekenreeks gesplitst in subtekenreeksen op basis van een opgegeven scheidingsteken en optioneel opties.
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()
Parameters
- separator
- Char
Een teken waarmee de subtekenreeksen in deze tekenreeks worden gescheiden.
- options
- StringSplitOptions
Een bitsgewijze combinatie van de opsommingswaarden die aangeeft of subtekenreeksen moeten worden ingekort en lege subtekenreeksen moeten worden opgenomen.
Retouren
Een matrix waarvan de elementen de subtekenreeksen van dit exemplaar bevatten die worden gescheiden door separator.
Van toepassing op
Split(ReadOnlySpan<Char>)
Splitst een tekenreeks in subtekenreeksen op basis van opgegeven scheidingstekens.
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()
Parameters
- separator
- ReadOnlySpan<Char>
Een reeks scheidingstekens of een lege span die geen scheidingstekens bevat.
Retouren
Een matrix waarvan de elementen de subtekenreeksen van dit exemplaar bevatten die worden gescheiden door een of meer tekens in separator.
Van toepassing op
Split(Char[])
Splitst een tekenreeks in subtekenreeksen op basis van opgegeven scheidingstekens.
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()
Parameters
- separator
- Char[]
Een matrix met scheidingstekens, een lege matrix die geen scheidingstekens bevat of null.
Retouren
Een matrix waarvan de elementen de subtekenreeksen van dit exemplaar bevatten die worden gescheiden door een of meer tekens in separator. Zie de sectie Opmerkingen voor meer informatie.
Voorbeelden
In het volgende voorbeeld ziet u hoe u afzonderlijke woorden uit een tekstblok extraheert door het spatieteken ( ) en tabteken (\t) als scheidingstekens te behandelen. De tekenreeks die wordt gesplitst, bevat beide tekens.
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
Opmerkingen
Wanneer een tekenreeks wordt gescheiden door een bekende set tekens, kunt u de Split(Char[]) methode gebruiken om deze te scheiden in subtekenreeksen.
Scheidingstekens worden niet opgenomen in de elementen van de geretourneerde matrix. Als de scheidingstekenmatrix bijvoorbeeld het teken '-' bevat en de waarde van het huidige tekenreeksexemplaren 'aa-bb-cc' is, retourneert de methode een matrix die drie elementen bevat: 'aa', 'bb' en 'cc'.
Als dit exemplaar geen tekens separatorbevat, bestaat de geretourneerde matrix uit één element dat dit exemplaar bevat.
Elk element van het definiëren van separator een afzonderlijk scheidingsteken. Als er twee scheidingstekens naast elkaar liggen of als er een scheidingsteken aan het begin of einde van dit exemplaar wordt gevonden, bevat Emptyhet bijbehorende element in de geretourneerde matrix.
In de volgende tabel ziet u enkele voorbeelden.
| Taal | Stringwaarde | Afscheider | Geretourneerde matrix |
|---|---|---|---|
| C# | "42, 12, 19" | new Char[] {',', ' '} | {"42", "", "12", "", "19"} |
| Visual Basic | "42, 12, 19" | Char() = {","c, " "c}) | {"42", "", "12", "", "19"} |
| C# | "42..12..19." | nieuw teken[] {'.'} | {"42", "", "12", "", "19", ""} |
| Visual Basic | "42..12..19." | Char() = {"." c} | {"42", "", "12", "", "19", ""} |
| C# | "Banaan" | nieuw teken[] {'.'} | {"Banaan"} |
| Visual Basic | "Banaan" | Char() = {"." c} | {"Banaan"} |
| C# | "Darb\nSmarba" | nieuw teken[] {} | {"Darb", "Smarba"} |
| Visual Basic | "Darb" & vbLf & "Smarba" | Char() = {} | {"Darb", "Smarba"} |
| C# | "Darb\nSmarba" | nul | {"Darb", "Smarba"} |
| Visual Basic | "Darb" & vbLf & "Smarba" | Niets | {"Darb", "Smarba"} |
De scheidingstekenmatrix
Elk scheidingsteken definieert een afzonderlijk scheidingsteken dat uit één teken bestaat.
Als het separator argument tekens bevat of geen null tekens bevat, worden witruimtetekens door de methode als scheidingstekens behandeld. Spatietekens worden gedefinieerd door de Unicode-standaard en de Char.IsWhiteSpace methode retourneert true als er een witruimteteken wordt doorgegeven.
String.Split(Char[]) en overbelastingsresolutie van compiler
Hoewel de enkele parameter voor deze overbelasting van String.Split een tekenmatrix is, kunt u deze met één teken aanroepen, zoals in het volgende voorbeeld wordt weergegeven.
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.
Omdat de separator parameter is ingericht met het ParamArrayAttribute kenmerk, interpreteren compilers één teken als een matrix met één element. Dit is niet het geval voor andere String.Split overbelastingen die een separator parameter bevatten. U moet deze overbelastingen expliciet doorgeven aan een tekenmatrix als argument separator .
Vergelijkingsdetails
De Split(Char[]) methode extraheert de subtekenreeksen in deze tekenreeks die worden gescheiden door een of meer tekens in de separator matrix en retourneert deze subtekenreeksen als elementen van een matrix.
De Split(Char[]) methode zoekt naar scheidingstekens door vergelijkingen uit te voeren met hoofdlettergevoelige ordinale sorteerregels. Zie de System.Globalization.CompareOptions opsomming voor meer informatie over woorden, tekenreeksen en rangschikkingen.
Prestatie-overwegingen
De Split methoden wijzen geheugen toe voor het geretourneerde matrixobject en een String object voor elk matrixelement. Als uw toepassing optimale prestaties vereist of als het beheren van geheugentoewijzing essentieel is in uw toepassing, kunt u overwegen de IndexOf of IndexOfAny methode te gebruiken. U kunt ook de Compare methode gebruiken om een subtekenreeks in een tekenreeks te zoeken.
Als u een tekenreeks wilt splitsen op een scheidingsteken, gebruikt u de IndexOf of IndexOfAny methode om een scheidingsteken in de tekenreeks te zoeken. Als u een tekenreeks wilt splitsen op een scheidingstekenreeks, gebruikt u de IndexOf of IndexOfAny methode om het eerste teken van de scheidingstekenreeks te zoeken. Gebruik vervolgens de Compare methode om te bepalen of de tekens na dat eerste teken gelijk zijn aan de resterende tekens van de scheidingstekenreeks.
Als dezelfde set tekens wordt gebruikt voor het splitsen van tekenreeksen in meerdere Split methode-aanroepen, kunt u ook één matrix maken en ernaar verwijzen in elke methode-aanroep. Dit vermindert de extra overhead van elke methode-aanroep aanzienlijk.
Notities voor bellers
Als in .NET Framework 3.5 en eerdere versies de methode Split(Char[]) wordt doorgegeven aan een separator die null of geen tekens bevat, gebruikt de methode een iets andere set witruimtetekens om de tekenreeks te splitsen dan de methode Trim(Char[]) om de tekenreeks te knippen. Vanaf .NET Framework 4 gebruiken beide methoden een identieke set Unicode-spatietekens.
Zie ook
- Char
- Concat(Object)
- Insert(Int32, String)
- Join(String, String[])
- Remove(Int32, Int32)
- Replace(Char, Char)
- Substring(Int32)
- Trim(Char[])
Van toepassing op
Split(String, StringSplitOptions)
Splitst een tekenreeks in subtekenreeksen die zijn gebaseerd op het opgegeven tekenreeksscheidingsteken.
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()
Parameters
- separator
- String
Een tekenreeks waarmee de subtekenreeksen in deze tekenreeks worden gescheiden.
- options
- StringSplitOptions
Een bitsgewijze combinatie van de opsommingswaarden die aangeeft of subtekenreeksen moeten worden ingekort en lege subtekenreeksen moeten worden opgenomen.
Retouren
Een matrix waarvan de elementen de subtekenreeksen van dit exemplaar bevatten die worden gescheiden door separator.