String.Split Metodo
Definizione
Importante
Alcune informazioni sono relative alla release non definitiva del prodotto, che potrebbe subire modifiche significative prima della release definitiva. Microsoft non riconosce alcuna garanzia, espressa o implicita, in merito alle informazioni qui fornite.
Restituisce una matrice di stringhe che contiene le sottostringhe in questa istanza delimitate da elementi di una stringa o di una matrice di caratteri Unicode specificata.
Overload
| Nome | Descrizione |
|---|---|
| Split(Rune, StringSplitOptions) | |
| Split(String[], Int32, StringSplitOptions) |
Suddivide una stringa in un numero massimo di sottostringhe in base alle stringhe di delimitazione specificate e, facoltativamente, alle opzioni. |
| Split(Rune, Int32, StringSplitOptions) | |
| Split(Char[], Int32, StringSplitOptions) |
Suddivide una stringa in un numero massimo di sottostringhe in base ai caratteri delimitatori specificati e, facoltativamente, alle opzioni. |
| Split(Char, Int32, StringSplitOptions) |
Suddivide una stringa in un numero massimo di sottostringhe in base al separatore di caratteri specificato, omettendo facoltativamente sottostringhe vuote dal risultato. |
| Split(String[], StringSplitOptions) |
Suddivide una stringa in sottostringhe in base a una stringa di delimitazione specificata e, facoltativamente, opzioni. |
| Split(String, Int32, StringSplitOptions) |
Suddivide una stringa in un numero massimo di sottostringhe in base a una stringa di delimitazione specificata e, facoltativamente, opzioni. |
| Split(Char[], StringSplitOptions) |
Suddivide una stringa in sottostringhe in base ai caratteri e alle opzioni di delimitazione specificati. |
| Split(Char[], Int32) |
Suddivide una stringa in un numero massimo di sottostringhe in base ai caratteri di delimitazione specificati. |
| Split(Char, StringSplitOptions) |
Suddivide una stringa in sottostringhe in base a un carattere di delimitazione specificato e, facoltativamente, opzioni. |
| Split(ReadOnlySpan<Char>) |
Suddivide una stringa in sottostringhe in base ai caratteri di delimitazione specificati. |
| Split(Char[]) |
Suddivide una stringa in sottostringhe in base ai caratteri di delimitazione specificati. |
| Split(String, StringSplitOptions) |
Suddivide una stringa in sottostringhe basate sul separatore di stringa specificato. |
Commenti
Split viene usato per suddividere una stringa delimitata in sottostringhe. È possibile usare una matrice di caratteri o una matrice di stringhe per specificare zero o più caratteri o stringhe delimitatori. Se non vengono specificati caratteri delimitatori, la stringa viene divisa in corrispondenza di spazi vuoti.
Gli overload del Split metodo consentono di limitare il numero di sottostringhe restituite dal metodo (il Split(Char[], Int32) metodo ), per specificare se includere stringhe vuote e/o tagliare le sottostringhe nel risultato (i Split(Char[], StringSplitOptions) metodi e Split(String[], StringSplitOptions) ) o eseguire entrambe le operazioni (i Split(Char[], Int32, StringSplitOptions) metodi e Split(String[], Int32, StringSplitOptions) ).
Mancia
Il Split metodo non è sempre il modo migliore per suddividere una stringa delimitata in sottostringhe. Se non si desidera estrarre tutte le sottostringhe di una stringa delimitata o se si vuole analizzare una stringa in base a un criterio anziché a un set di caratteri delimitatori, è consigliabile usare espressioni regolari o combinare uno dei metodi di ricerca che restituisce l'indice di un carattere con il Substring metodo . Per altre informazioni, vedere Estrarre sottostringhe da una stringa.
Esempio
Gli esempi seguenti illustrano tre diversi sovraccarichi di String.Split(). Il primo esempio chiama l'overload Split(Char[]) e passa un singolo delimitatore.
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.
Come si può notare, i caratteri punto (.) sono inclusi in due delle sottostringhe. Se si desidera escludere i caratteri punto, è possibile aggiungere il carattere punto come carattere delimitatore aggiuntivo. Nell'esempio seguente viene illustrato come eseguire questa operazione.
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:
I periodi sono passati dalle sottostringhe, ma ora sono state incluse due sottostringhe vuote aggiuntive. Queste sottostringa vuota rappresentano la sottostringa tra una parola e il punto che lo segue. Per omettere le sottostringhe vuote dalla matrice risultante, è possibile chiamare l'overload Split(Char[], StringSplitOptions) e specificare StringSplitOptions.RemoveEmptyEntries per il parametro options.
string s = "You win some. You lose some.";
char[] separators = new char[] { ' ', '.' };
string[] subs = s.Split(separators, StringSplitOptions.RemoveEmptyEntries);
foreach (var sub in subs)
{
Console.WriteLine($"Substring: {sub}");
}
// This example produces the following output:
//
// Substring: You
// Substring: win
// Substring: some
// Substring: You
// Substring: lose
// Substring: some
let s = "You win some. You lose some."
let separators = [| ' '; '.' |]
let subs = s.Split(separators, StringSplitOptions.RemoveEmptyEntries)
for sub in subs do
printfn $"Substring: {sub}"
// This example produces the following output:
//
// Substring: You
// Substring: win
// Substring: some
// Substring: You
// Substring: lose
// Substring: some
Dim s As String = "You win some. You lose some."
Dim separators As Char() = New Char() {" "c, "."c}
Dim subs As String() = s.Split(separators, StringSplitOptions.RemoveEmptyEntries)
For Each substring As String In subs
Console.WriteLine($"Substring: {substring}")
Next
' This example produces the following output:
'
' Substring: You
' Substring: win
' Substring: some
' Substring: You
' Substring: lose
' Substring: some
Le sezioni per i singoli overload di String.Split() contengono altri esempi.
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()
Parametri
- separator
- Rune
- options
- StringSplitOptions
Restituisce
Si applica a
Split(String[], Int32, StringSplitOptions)
- Origine:
- String.Manipulation.cs
- Origine:
- String.Manipulation.cs
- Origine:
- String.Manipulation.cs
- Origine:
- String.Manipulation.cs
Suddivide una stringa in un numero massimo di sottostringhe in base alle stringhe di delimitazione specificate e, facoltativamente, alle opzioni.
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()
Parametri
- separator
- String[]
Stringhe che delimitano le sottostringhe in questa stringa, una matrice vuota che non contiene delimitatori o null.
- count
- Int32
Numero massimo di sottostringhe da restituire.
- options
- StringSplitOptions
Combinazione bit per bit dei valori di enumerazione che specifica se tagliare le sottostringhe e includere sottostringhe vuote.
Restituisce
Matrice i cui elementi contengono le sottostringhe in questa stringa delimitate da una o più stringhe in separator. Per altre informazioni, vedere la sezione Osservazioni.
- Attributi
Eccezioni
count è negativo.
options non è uno dei StringSplitOptions valori.
Esempio
Nell'esempio seguente viene utilizzata l'enumerazione StringSplitOptions per includere o escludere sottostringhe generate dal Split metodo .
// 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]>
'
Commenti
Le stringhe delimitatori non sono incluse negli elementi della matrice restituita.
Se questa istanza non contiene alcuna stringa in separatoro il parametro è 1, la count matrice restituita è costituita da un singolo elemento che contiene questa istanza.
Se il separator parametro è null o non contiene caratteri, si presuppone che gli spazi vuoti siano i delimitatori. Gli spazi vuoti sono definiti dallo standard Unicode e il Char.IsWhiteSpace metodo restituisce true se vengono passati.
Per passare null per il string[] separator parametro, è necessario indicare il tipo di null per evitare ambiguità con la chiamata da altri overload, ad esempio Split(Char[], Int32, StringSplitOptions). Nell'esempio seguente vengono illustrati diversi modi per identificare in modo univoco questo overload.
string phrase = "The quick brown fox";
_ = phrase.Split(default(string[]), 3, StringSplitOptions.RemoveEmptyEntries);
_ = phrase.Split((string[]?)null, 3, StringSplitOptions.RemoveEmptyEntries);
_ = phrase.Split(null as string[], 3, StringSplitOptions.RemoveEmptyEntries);
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)
Se il count parametro è zero o il options parametro è RemoveEmptyEntries e la lunghezza di questa istanza è zero, viene restituita una matrice vuota.
Ogni elemento di separator definisce un delimitatore separato costituito da uno o più caratteri. Se il options parametro è Nonee due delimitatori sono adiacenti o viene trovato un delimitatore all'inizio o alla fine di questa istanza, l'elemento della matrice corrispondente contiene Empty.
Se in questa istanza sono presenti più count sottostringhe, le prime count meno 1 sottostringhe vengono restituite nei primi count meno 1 elementi del valore restituito e i caratteri rimanenti in questa istanza vengono restituiti nell'ultimo elemento del valore restituito.
Se count è maggiore del numero di sottostringhe, vengono restituite le sottostringhe disponibili e non viene generata alcuna eccezione.
Matrice separatore
Se uno degli elementi in separator è costituito da più caratteri, l'intera sottostringa viene considerata un delimitatore. Ad esempio, se uno degli elementi in separator è "10", il tentativo di dividere la stringa "This10is10a10string". restituisce questa matrice di quattro elementi: { "This", "is", "a", "string". }.
Dettagli confronto
Il Split metodo estrae le sottostringhe in questa stringa delimitate da una o più stringhe nel separator parametro e restituisce tali sottostringhe come elementi di una matrice.
Il Split metodo cerca i delimitatori eseguendo confronti usando regole di ordinamento ordinale con distinzione tra maiuscole e minuscole. Per altre informazioni sugli ordinali di parole, stringhe e ordinali, vedere l'enumerazione System.Globalization.CompareOptions .
Il Split metodo ignora qualsiasi elemento del separator cui valore è null o la stringa vuota ("").
Per evitare risultati ambigui quando le stringhe in separator hanno caratteri in comune, il Split metodo procede dall'inizio alla fine del valore dell'istanza e corrisponde al primo elemento in separator che è uguale a un delimitatore nell'istanza di . L'ordine in cui vengono rilevate sottostringhe nell'istanza ha la precedenza sull'ordine degli elementi in separator.
Si consideri ad esempio un'istanza il cui valore è "abcdef". Se il primo elemento in separator è "ef" e il secondo elemento è "bcde", il risultato dell'operazione di divisione sarà "a" e "f". Ciò è dovuto al fatto che viene rilevata la sottostringa nell'istanza "bcde" e corrisponde a un elemento in separator prima che venga rilevata la sottostringa "f".
Tuttavia, se il primo elemento di separator è "bcd" e il secondo elemento è "bc", il risultato dell'operazione di divisione sarà "a" e "ef". Questo perché "bcd" è il primo delimitatore in separator che corrisponde a un delimitatore nell'istanza di . Se l'ordine dei separatori è stato invertito in modo che il primo elemento fosse "bc" e il secondo elemento fosse "bcd", il risultato sarebbe "a" e "def".
Considerazioni sulle prestazioni
I Split metodi allocano memoria per l'oggetto matrice restituito e un String oggetto per ogni elemento della matrice. Se l'applicazione richiede prestazioni ottimali o se la gestione dell'allocazione di memoria è fondamentale nell'applicazione, è consigliabile usare il IndexOf metodo o IndexOfAny e, facoltativamente, per Compare individuare una sottostringa all'interno di una stringa.
Se si divide una stringa in corrispondenza di un carattere separatore, utilizzare il IndexOf metodo o IndexOfAny per individuare un carattere separatore nella stringa. Se si divide una stringa in corrispondenza di una stringa separatore, utilizzare il IndexOf metodo o IndexOfAny per individuare il primo carattere della stringa separatore. Usare quindi il Compare metodo per determinare se i caratteri dopo il primo carattere sono uguali ai caratteri rimanenti della stringa separatore.
Inoltre, se lo stesso set di caratteri viene usato per suddividere le stringhe in più Split chiamate di metodo, è consigliabile creare una singola matrice e farvi riferimento in ogni chiamata al metodo. In questo modo si riduce significativamente il sovraccarico aggiuntivo di ogni chiamata al metodo.
Note per i chiamanti
In .NET Framework 3.5 e versioni precedenti, se il Split(Char[]) metodo viene passato a che separator è null o non contiene caratteri, il metodo usa un set leggermente diverso di caratteri di spazi vuoti per dividere la stringa rispetto Trim(Char[]) al metodo per tagliare la stringa. A partire da .NET Framework 4, entrambi i metodi usano un set identico di spazi vuoti Unicode.
Si applica a
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()
Parametri
- separator
- Rune
- count
- Int32
- options
- StringSplitOptions
Restituisce
Si applica a
Split(Char[], Int32, StringSplitOptions)
- Origine:
- String.Manipulation.cs
- Origine:
- String.Manipulation.cs
- Origine:
- String.Manipulation.cs
- Origine:
- String.Manipulation.cs
Suddivide una stringa in un numero massimo di sottostringhe in base ai caratteri delimitatori specificati e, facoltativamente, alle opzioni.
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()
Parametri
- separator
- Char[]
Matrice di caratteri che delimitano le sottostringhe in questa stringa, una matrice vuota che non contiene delimitatori o null.
- count
- Int32
Numero massimo di sottostringhe da restituire.
- options
- StringSplitOptions
Combinazione bit per bit dei valori di enumerazione che specifica se tagliare le sottostringhe e includere sottostringhe vuote.
Restituisce
Matrice che contiene le sottostringhe in questa stringa delimitate da uno o più caratteri in separator. Per altre informazioni, vedere la sezione Osservazioni.
- Attributi
Eccezioni
count è negativo.
options non è uno dei StringSplitOptions valori.
Esempio
Nell'esempio seguente viene utilizzata l'enumerazione StringSplitOptions per includere o escludere sottostringhe generate dal Split metodo .
// 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]>
'
Commenti
I caratteri delimitatori non sono inclusi negli elementi della matrice restituita.
Se questa istanza non contiene alcun carattere in separatoro il parametro è 1, la count matrice restituita è costituita da un singolo elemento che contiene questa istanza.
Se il separator parametro è null o non contiene caratteri, si presuppone che gli spazi vuoti siano i delimitatori. Gli spazi vuoti sono definiti dallo standard Unicode e il Char.IsWhiteSpace metodo restituisce true se vengono passati.
Per passare null per il char[] separator parametro, è necessario indicare il tipo di null per evitare ambiguità con la chiamata da altri overload, ad esempio Split(String[], Int32, StringSplitOptions). Nell'esempio seguente vengono illustrati diversi modi per identificare in modo univoco questo overload.
string phrase = "The quick brown fox";
_ = phrase.Split(default(char[]), 3, StringSplitOptions.RemoveEmptyEntries);
_ = phrase.Split((char[]?)null, 3, StringSplitOptions.RemoveEmptyEntries);
_ = phrase.Split(null as char[], 3, StringSplitOptions.RemoveEmptyEntries);
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)
Se il count parametro è zero o il options parametro è RemoveEmptyEntries e la lunghezza di questa istanza è zero, viene restituita una matrice vuota.
Ogni elemento di separator definisce un carattere delimitatore separato. Se il options parametro è Nonee due delimitatori sono adiacenti o viene trovato un delimitatore all'inizio o alla fine di questa istanza, l'elemento della matrice corrispondente contiene Empty.
Se in questa istanza sono presenti più count sottostringhe, le prime count meno 1 sottostringhe vengono restituite nei primi count meno 1 elementi del valore restituito e i caratteri rimanenti in questa istanza vengono restituiti nell'ultimo elemento del valore restituito.
Se count è maggiore del numero di sottostringhe, vengono restituite le sottostringhe disponibili e non viene generata alcuna eccezione.
Considerazioni sulle prestazioni
I Split metodi allocano memoria per l'oggetto matrice restituito e un String oggetto per ogni elemento della matrice. Se l'applicazione richiede prestazioni ottimali o se la gestione dell'allocazione di memoria è fondamentale nell'applicazione, è consigliabile usare il IndexOf metodo o IndexOfAny e, facoltativamente, per Compare individuare una sottostringa all'interno di una stringa.
Se si divide una stringa in corrispondenza di un carattere separatore, utilizzare il IndexOf metodo o IndexOfAny per individuare un carattere separatore nella stringa. Se si divide una stringa in corrispondenza di una stringa separatore, utilizzare il IndexOf metodo o IndexOfAny per individuare il primo carattere della stringa separatore. Usare quindi il Compare metodo per determinare se i caratteri dopo il primo carattere sono uguali ai caratteri rimanenti della stringa separatore.
Inoltre, se lo stesso set di caratteri viene usato per suddividere le stringhe in più Split chiamate di metodo, è consigliabile creare una singola matrice e farvi riferimento in ogni chiamata al metodo. In questo modo si riduce significativamente il sovraccarico aggiuntivo di ogni chiamata al metodo.
Note per i chiamanti
In .NET Framework 3.5 e versioni precedenti, se il Split(Char[]) metodo viene passato a che separator è null o non contiene caratteri, il metodo usa un set leggermente diverso di caratteri di spazi vuoti per dividere la stringa rispetto Trim(Char[]) al metodo per tagliare la stringa. A partire da .NET Framework 4, entrambi i metodi usano un set identico di spazi vuoti Unicode.
Si applica a
Split(Char, Int32, StringSplitOptions)
- Origine:
- String.Manipulation.cs
- Origine:
- String.Manipulation.cs
- Origine:
- String.Manipulation.cs
- Origine:
- String.Manipulation.cs
Suddivide una stringa in un numero massimo di sottostringhe in base al separatore di caratteri specificato, omettendo facoltativamente sottostringhe vuote dal risultato.
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()
Parametri
- separator
- Char
Carattere che delimita le sottostringhe in questa istanza.
- count
- Int32
Numero massimo di elementi previsti nella matrice.
- options
- StringSplitOptions
Combinazione bit per bit dei valori di enumerazione che specifica se tagliare le sottostringhe e includere sottostringhe vuote.
Restituisce
Matrice che contiene al massimo count sottostringhe di questa istanza delimitate da separator.
Commenti
Se la stringa è già stata divisa count - 1 volte, ma la fine della stringa non è stata raggiunta, l'ultima stringa nella matrice restituita conterrà la sottostringa finale rimanente di questa istanza, non toccato.
Si applica a
Split(String[], StringSplitOptions)
- Origine:
- String.Manipulation.cs
- Origine:
- String.Manipulation.cs
- Origine:
- String.Manipulation.cs
- Origine:
- String.Manipulation.cs
Suddivide una stringa in sottostringhe in base a una stringa di delimitazione specificata e, facoltativamente, opzioni.
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()
Parametri
- separator
- String[]
Matrice di stringhe che delimitano le sottostringhe in questa stringa, una matrice vuota che non contiene delimitatori o null.
- options
- StringSplitOptions
Combinazione bit per bit dei valori di enumerazione che specifica se tagliare le sottostringhe e includere sottostringhe vuote.
Restituisce
Matrice i cui elementi contengono le sottostringhe in questa stringa delimitate da una o più stringhe in separator. Per altre informazioni, vedere la sezione Osservazioni.
- Attributi
Eccezioni
options non è uno dei StringSplitOptions valori.
Esempio
Nell'esempio seguente viene illustrata la differenza nelle matrici restituite chiamando il metodo di String.Split(String[], StringSplitOptions) una stringa con il relativo options parametro uguale a StringSplitOptions.None e 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'
Nell'esempio seguente viene definita una matrice di separatori che includono segni di punteggiatura e spazi vuoti. Il passaggio di questa matrice insieme a un valore di StringSplitOptions.RemoveEmptyEntries al Split(String[], StringSplitOptions) metodo restituisce una matrice costituita dalle singole parole della stringa.
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
Si noti che il metodo viene chiamato con l'argomento options impostato su StringSplitOptions.RemoveEmptyEntries. Ciò impedisce alla matrice restituita di includere String.Empty valori che rappresentano corrispondenze di sottostringa vuote tra segni di punteggiatura e spazi vuoti.
Commenti
Quando una stringa è delimitata da un set noto di stringhe, è possibile usare il Split metodo per separarla in sottostringhe.
Le stringhe delimitatori non sono incluse negli elementi della matrice restituita. Ad esempio, se la separator matrice include la stringa "--" e il valore dell'istanza di stringa corrente è "aa--bb--cc", il metodo restituisce una matrice che contiene tre elementi: "aa", "bb" e "cc".
Se questa istanza non contiene alcuna stringa in separator, la matrice restituita è costituita da un singolo elemento che contiene questa istanza.
Se il options parametro è RemoveEmptyEntries e la lunghezza di questa istanza è zero, il metodo restituisce una matrice vuota.
Ogni elemento di separator definisce un delimitatore separato costituito da uno o più caratteri. Se l'argomento options è Nonee due delimitatori sono adiacenti o viene trovato un delimitatore all'inizio o alla fine di questa istanza, l'elemento della matrice corrispondente contiene String.Empty. Ad esempio, se separator include due elementi, "-" e "_", il valore dell'istanza di stringa è "-_aa-_" e il valore dell'argomento options è None, il metodo restituisce una matrice di stringhe con i cinque elementi seguenti:
String.Empty, che rappresenta la stringa vuota che precede la sottostringa "-" in corrispondenza dell'indice 0.
String.Empty, che rappresenta la stringa vuota tra la sottostringa "-" in corrispondenza dell'indice 0 e la sottostringa "_" in corrispondenza dell'indice 1.
"aa".
String.Empty, che rappresenta la stringa vuota che segue la sottostringa "-" in corrispondenza dell'indice 4.
String.Empty, che rappresenta la stringa vuota che segue la sottostringa "_" in corrispondenza dell'indice 5.
Matrice separatore
Se uno degli elementi in separator è costituito da più caratteri, l'intera sottostringa viene considerata un delimitatore. Ad esempio, se uno degli elementi in separator è "10", il tentativo di dividere la stringa "This10is10a10string" restituisce la matrice di quattro elementi seguente: { "This", "is", "a", "string". }.
Se il separator parametro è null o non contiene stringhe non vuote, si presuppone che gli spazi vuoti siano i delimitatori. Gli spazi vuoti sono definiti dallo standard Unicode e il Char.IsWhiteSpace metodo restituisce true se vengono passati.
Per passare null per il string[] separator parametro, è necessario indicare il tipo di null per evitare ambiguità con la chiamata da altri overload, ad esempio Split(Char[], StringSplitOptions). Nell'esempio seguente vengono illustrati diversi modi per identificare in modo univoco questo overload.
string phrase = "The quick brown fox";
_ = phrase.Split(default(string[]), StringSplitOptions.RemoveEmptyEntries);
_ = phrase.Split((string[]?)null, StringSplitOptions.RemoveEmptyEntries);
_ = phrase.Split(null as string[], StringSplitOptions.RemoveEmptyEntries);
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)
Dettagli confronto
Il Split metodo estrae le sottostringhe in questa stringa delimitate da una o più stringhe nel separator parametro e restituisce tali sottostringhe come elementi di una matrice.
Il Split metodo cerca i delimitatori eseguendo confronti usando regole di ordinamento ordinale con distinzione tra maiuscole e minuscole. Per altre informazioni sugli ordinali di parole, stringhe e ordinali, vedere l'enumerazione System.Globalization.CompareOptions .
Il Split metodo ignora qualsiasi elemento del separator cui valore è null o la stringa vuota ("").
Per evitare risultati ambigui quando le stringhe in separator hanno caratteri in comune, l'operazione Split procede dall'inizio alla fine del valore dell'istanza e corrisponde al primo elemento in separator che è uguale a un delimitatore nell'istanza di . L'ordine in cui vengono rilevate sottostringhe nell'istanza ha la precedenza sull'ordine degli elementi in separator.
Si consideri ad esempio un'istanza il cui valore è "abcdef". Se il primo elemento in separator è "ef" e il secondo elemento è "bcde", il risultato dell'operazione di divisione sarà una matrice di stringhe che contiene due elementi, "a" e "f". Ciò è dovuto al fatto che viene rilevata la sottostringa nell'istanza "bcde" e corrisponde a un elemento in separator prima che venga rilevata la sottostringa "f".
Tuttavia, se il primo elemento di separator è "bcd" e il secondo elemento era "bc", il risultato dell'operazione di divisione sarebbe una matrice di stringhe che contiene due elementi, "a" e "ef". Questo perché "bcd" è il primo delimitatore in separator che corrisponde a un delimitatore nell'istanza di . Se l'ordine dei separatori è stato invertito in modo che il primo elemento fosse "bc" e il secondo elemento fosse "bcd", il risultato sarebbe una matrice di stringhe che contiene due elementi, "a" e "def".
Considerazioni sulle prestazioni
I Split metodi allocano memoria per l'oggetto matrice restituito e un String oggetto per ogni elemento della matrice. Se l'applicazione richiede prestazioni ottimali o se la gestione dell'allocazione di memoria è fondamentale nell'applicazione, è consigliabile usare il IndexOf metodo o IndexOfAny e, facoltativamente, per Compare individuare una sottostringa all'interno di una stringa.
Se si divide una stringa in corrispondenza di un carattere separatore, utilizzare il IndexOf metodo o IndexOfAny per individuare un carattere separatore nella stringa. Se si divide una stringa in corrispondenza di una stringa separatore, utilizzare il IndexOf metodo o IndexOfAny per individuare il primo carattere della stringa separatore. Usare quindi il Compare metodo per determinare se i caratteri dopo il primo carattere sono uguali ai caratteri rimanenti della stringa separatore.
Inoltre, se lo stesso set di caratteri viene usato per suddividere le stringhe in più Split chiamate di metodo, è consigliabile creare una singola matrice e farvi riferimento in ogni chiamata al metodo. In questo modo si riduce significativamente il sovraccarico aggiuntivo di ogni chiamata al metodo.
Note per i chiamanti
In .NET Framework 3.5 e versioni precedenti, se il Split(Char[]) metodo viene passato a che separator è null o non contiene caratteri, il metodo usa un set leggermente diverso di caratteri di spazi vuoti per dividere la stringa rispetto Trim(Char[]) al metodo per tagliare la stringa. A partire da .NET Framework 4, entrambi i metodi usano un set identico di spazi vuoti Unicode.
Si applica a
Split(String, Int32, StringSplitOptions)
- Origine:
- String.Manipulation.cs
- Origine:
- String.Manipulation.cs
- Origine:
- String.Manipulation.cs
- Origine:
- String.Manipulation.cs
Suddivide una stringa in un numero massimo di sottostringhe in base a una stringa di delimitazione specificata e, facoltativamente, opzioni.
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()
Parametri
- separator
- String
Stringa che delimita le sottostringhe in questa istanza.
- count
- Int32
Numero massimo di elementi previsti nella matrice.
- options
- StringSplitOptions
Combinazione bit per bit dei valori di enumerazione che specifica se tagliare le sottostringhe e includere sottostringhe vuote.
Restituisce
Matrice che contiene al massimo count sottostringhe di questa istanza delimitate da separator.
Commenti
Se la stringa è già stata divisa count - 1 volte, ma la fine della stringa non è stata raggiunta, l'ultima stringa nella matrice restituita conterrà la sottostringa finale rimanente di questa istanza, non toccato.
Si applica a
Split(Char[], StringSplitOptions)
- Origine:
- String.Manipulation.cs
- Origine:
- String.Manipulation.cs
- Origine:
- String.Manipulation.cs
- Origine:
- String.Manipulation.cs
Suddivide una stringa in sottostringhe in base ai caratteri e alle opzioni di delimitazione specificati.
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()
Parametri
- separator
- Char[]
Matrice di caratteri che delimitano le sottostringhe in questa stringa, una matrice vuota che non contiene delimitatori o null.
- options
- StringSplitOptions
Combinazione bit per bit dei valori di enumerazione che specifica se tagliare le sottostringhe e includere sottostringhe vuote.
Restituisce
Matrice i cui elementi contengono le sottostringhe in questa stringa delimitate da uno o più caratteri in separator. Per altre informazioni, vedere la sezione Osservazioni.
- Attributi
Eccezioni
options non è uno dei StringSplitOptions valori.
Esempio
Nell'esempio seguente viene utilizzata l'enumerazione StringSplitOptions per includere o escludere sottostringhe generate dal Split metodo .
// 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]>
'
Commenti
I caratteri delimitatori (i caratteri nella separator matrice) non sono inclusi negli elementi della matrice restituita. Ad esempio, se la separator matrice include il carattere "-" e il valore dell'istanza di stringa corrente è "aa-bb-cc", il metodo restituisce una matrice che contiene tre elementi: "aa", "bb" e "cc".
Se questa istanza non contiene alcun carattere in separator, la matrice restituita è costituita da un singolo elemento che contiene questa istanza.
Se il options parametro è RemoveEmptyEntries e la lunghezza di questa istanza è zero, il metodo restituisce una matrice vuota.
Ogni elemento di separator definisce un delimitatore separato costituito da un singolo carattere. Se l'argomento options è Nonee due delimitatori sono adiacenti o viene trovato un delimitatore all'inizio o alla fine di questa istanza, l'elemento della matrice corrispondente contiene String.Empty. Ad esempio, se separator include due elementi '-' e '_', il valore dell'istanza della stringa è "-_aa-_" e il valore dell'argomento options è None, il metodo restituisce una matrice di stringhe con i cinque elementi seguenti:
String.Empty, che rappresenta la stringa vuota che precede il carattere "-" in corrispondenza dell'indice 0.
String.Empty, che rappresenta la stringa vuota tra il carattere "-" in corrispondenza dell'indice 0 e il carattere "_" in corrispondenza dell'indice 1.
"aa".
String.Empty, che rappresenta la stringa vuota che segue il carattere "-" in corrispondenza dell'indice 4.
String.Empty, che rappresenta la stringa vuota che segue il carattere "_" in corrispondenza dell'indice 5.
Matrice separatore
Se il separator parametro è null o non contiene caratteri, si presuppone che gli spazi vuoti siano i delimitatori. Gli spazi vuoti sono definiti dallo standard Unicode e il Char.IsWhiteSpace metodo restituisce true se vengono passati.
Per passare null per il char[] separator parametro, è necessario indicare il tipo di null per evitare ambiguità con la chiamata da altri overload, ad esempio Split(String[], StringSplitOptions). Nell'esempio seguente vengono illustrati diversi modi per identificare in modo univoco questo overload.
string phrase = "The quick brown fox";
_ = phrase.Split(default(char[]), StringSplitOptions.RemoveEmptyEntries);
_ = phrase.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries);
_ = phrase.Split(null as char[], StringSplitOptions.RemoveEmptyEntries);
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)
Dettagli confronto
Il Split metodo estrae le sottostringhe in questa stringa delimitate da uno o più caratteri nel separator parametro e restituisce tali sottostringhe come elementi di una matrice.
Il Split metodo cerca i delimitatori eseguendo confronti usando regole di ordinamento ordinale con distinzione tra maiuscole e minuscole. Per altre informazioni sugli ordinali di parole, stringhe e ordinali, vedere l'enumerazione System.Globalization.CompareOptions .
Considerazioni sulle prestazioni
I Split metodi allocano memoria per l'oggetto matrice restituito e un String oggetto per ogni elemento della matrice. Se l'applicazione richiede prestazioni ottimali o se la gestione dell'allocazione di memoria è fondamentale nell'applicazione, è consigliabile usare il IndexOf metodo o IndexOfAny e, facoltativamente, per Compare individuare una sottostringa all'interno di una stringa.
Se si divide una stringa in corrispondenza di un carattere separatore, utilizzare il IndexOf metodo o IndexOfAny per individuare un carattere separatore nella stringa. Se si divide una stringa in corrispondenza di una stringa separatore, utilizzare il IndexOf metodo o IndexOfAny per individuare il primo carattere della stringa separatore. Usare quindi il Compare metodo per determinare se i caratteri dopo il primo carattere sono uguali ai caratteri rimanenti della stringa separatore.
Inoltre, se lo stesso set di caratteri viene usato per suddividere le stringhe in più Split chiamate di metodo, è consigliabile creare una singola matrice e farvi riferimento in ogni chiamata al metodo. In questo modo si riduce significativamente il sovraccarico aggiuntivo di ogni chiamata al metodo.
Note per i chiamanti
In .NET Framework 3.5 e versioni precedenti, se il Split(Char[]) metodo viene passato a che separator è null o non contiene caratteri, il metodo usa un set leggermente diverso di caratteri di spazi vuoti per dividere la stringa rispetto Trim(Char[]) al metodo per tagliare la stringa. A partire da .NET Framework 4, entrambi i metodi usano un set identico di spazi vuoti Unicode.
Si applica a
Split(Char[], Int32)
- Origine:
- String.Manipulation.cs
- Origine:
- String.Manipulation.cs
- Origine:
- String.Manipulation.cs
- Origine:
- String.Manipulation.cs
Suddivide una stringa in un numero massimo di sottostringhe in base ai caratteri di delimitazione specificati.
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()
Parametri
- separator
- Char[]
Matrice di caratteri che delimitano le sottostringhe in questa stringa, una matrice vuota che non contiene delimitatori o null.
- count
- Int32
Numero massimo di sottostringhe da restituire.
Restituisce
Matrice i cui elementi contengono le sottostringhe in questa istanza delimitate da uno o più caratteri in separator. Per altre informazioni, vedere la sezione Osservazioni.
Eccezioni
count è negativo.
Esempio
Nell'esempio seguente viene illustrato come count usare per limitare il numero di stringhe restituite da 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"
Commenti
I caratteri delimitatori non sono inclusi negli elementi della matrice restituita.
Se questa istanza non contiene alcun carattere in separator, la matrice restituita è costituita da un singolo elemento che contiene questa istanza. Se count è zero, viene restituita una matrice vuota.
Se il separator parametro è null o non contiene caratteri, si presuppone che gli spazi vuoti siano i delimitatori. Gli spazi vuoti sono definiti dallo standard Unicode e il Char.IsWhiteSpace metodo restituisce true se vengono passati.
Ogni elemento di separator definisce un carattere delimitatore separato. Se due delimitatori sono adiacenti o viene trovato un delimitatore all'inizio o alla fine di questa istanza, l'elemento della matrice corrispondente contiene Empty.
Se in questa istanza sono presenti più count sottostringhe, le prime count - 1 sottostringhe vengono restituite nei primi count - 1 elementi del valore restituito e i caratteri rimanenti in questa istanza vengono restituiti nell'ultimo elemento del valore restituito.
Se count è maggiore del numero di sottostringhe, vengono restituite le sottostringhe disponibili e non viene generata alcuna eccezione.
La tabella seguente illustra alcuni esempi.
| Lingua | Valore stringa | Separatore | Matrice restituita |
|---|---|---|---|
| C# | "42, 12, 19" | new Char[] {',', ' '} | {"42", "", "12", "", "19"} |
| Visual Basic | "42, 12, 19" | Char() = {","c, " "c}) | {"42", "", "12", "", "19"} |
| C# | "42..12..19." | new Char[] {'.'} | {"42", "", "12", "", "19", ""} |
| Visual Basic | "42..12..19." | Char() = {"." c} | {"42", "", "12", "", "19", ""} |
| C# | "Banana" | new Char[] {'.'} | {"Banana"} |
| Visual Basic | "Banana" | Char() = {"." c} | {"Banana"} |
| C# | "Darb\nSmarba" | new Char[] {} | {"Darb", "Smarba"} |
| Visual Basic | "Darb" & vbLf & "Smarba" | Char() = {} | {"Darb", "Smarba"} |
| C# | "Darb\nSmarba" | nullo | {"Darb", "Smarba"} |
| Visual Basic | "Darb" & vbLf & "Smarba" | Niente | {"Darb", "Smarba"} |
Considerazioni sulle prestazioni
I Split metodi allocano memoria per l'oggetto matrice restituito e un String oggetto per ogni elemento della matrice. Se l'applicazione richiede prestazioni ottimali o se la gestione dell'allocazione di memoria è fondamentale nell'applicazione, è consigliabile usare il IndexOf metodo o IndexOfAny e, facoltativamente, per Compare individuare una sottostringa all'interno di una stringa.
Se si divide una stringa in corrispondenza di un carattere separatore, utilizzare il IndexOf metodo o IndexOfAny per individuare un carattere separatore nella stringa. Se si divide una stringa in corrispondenza di una stringa separatore, utilizzare il IndexOf metodo o IndexOfAny per individuare il primo carattere della stringa separatore. Usare quindi il Compare metodo per determinare se i caratteri dopo il primo carattere sono uguali ai caratteri rimanenti della stringa separatore.
Inoltre, se lo stesso set di caratteri viene usato per suddividere le stringhe in più Split chiamate di metodo, è consigliabile creare una singola matrice e farvi riferimento in ogni chiamata al metodo. In questo modo si riduce significativamente il sovraccarico aggiuntivo di ogni chiamata al metodo.
Note per i chiamanti
In .NET Framework 3.5 e versioni precedenti, se il Split(Char[]) metodo viene passato a che separator è null o non contiene caratteri, il metodo usa un set leggermente diverso di caratteri di spazi vuoti per dividere la stringa rispetto Trim(Char[]) al metodo per tagliare la stringa. A partire da .NET Framework 4, entrambi i metodi usano un set identico di spazi vuoti Unicode.
Vedi anche
- Char
- Array
- Int32
- Concat(Object)
- Insert(Int32, String)
- Join(String, String[])
- Remove(Int32, Int32)
- Replace(Char, Char)
- Substring(Int32)
- Trim(Char[])
Si applica a
Split(Char, StringSplitOptions)
- Origine:
- String.Manipulation.cs
- Origine:
- String.Manipulation.cs
- Origine:
- String.Manipulation.cs
- Origine:
- String.Manipulation.cs
Suddivide una stringa in sottostringhe in base a un carattere di delimitazione specificato e, facoltativamente, opzioni.
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()
Parametri
- separator
- Char
Carattere che delimita le sottostringhe in questa stringa.
- options
- StringSplitOptions
Combinazione bit per bit dei valori di enumerazione che specifica se tagliare le sottostringhe e includere sottostringhe vuote.
Restituisce
Matrice i cui elementi contengono le sottostringhe di questa istanza delimitate da separator.
Si applica a
Split(ReadOnlySpan<Char>)
- Origine:
- String.Manipulation.cs
Suddivide una stringa in sottostringhe in base ai caratteri di delimitazione specificati.
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()
Parametri
- separator
- ReadOnlySpan<Char>
Intervallo di caratteri delimitatori o intervallo vuoto che non contiene delimitatori.
Restituisce
Matrice i cui elementi contengono le sottostringhe di questa istanza delimitate da uno o più caratteri in separator.
Si applica a
Split(Char[])
- Origine:
- String.Manipulation.cs
- Origine:
- String.Manipulation.cs
- Origine:
- String.Manipulation.cs
- Origine:
- String.Manipulation.cs
Suddivide una stringa in sottostringhe in base ai caratteri di delimitazione specificati.
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()
Parametri
- separator
- Char[]
Matrice di caratteri delimitatori, matrice vuota che non contiene delimitatori o null.
Restituisce
Matrice i cui elementi contengono le sottostringhe di questa istanza delimitate da uno o più caratteri in separator. Per altre informazioni, vedere la sezione Osservazioni.
Esempio
Nell'esempio seguente viene illustrato come estrarre singole parole da un blocco di testo trattando lo spazio () e il carattere di tabulazione ( \t) come delimitatori. La stringa divisa include entrambi questi caratteri.
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
Commenti
Quando una stringa è delimitata da un set di caratteri noto, è possibile usare il Split(Char[]) metodo per separarla in sottostringhe.
I caratteri delimitatori non sono inclusi negli elementi della matrice restituita. Ad esempio, se la matrice separatore include il carattere "-" e il valore dell'istanza di stringa corrente è "aa-bb-cc", il metodo restituisce una matrice che contiene tre elementi: "aa", "bb" e "cc".
Se questa istanza non contiene alcun carattere in separator, la matrice restituita è costituita da un singolo elemento che contiene questa istanza.
Ogni elemento di separator definisce un carattere delimitatore separato. Se due delimitatori sono adiacenti o viene trovato un delimitatore all'inizio o alla fine di questa istanza, l'elemento corrispondente nella matrice restituita contiene Empty.
La tabella seguente illustra alcuni esempi.
| Lingua | Valore stringa | Separatore | Matrice restituita |
|---|---|---|---|
| C# | "42, 12, 19" | new Char[] {',', ' '} | {"42", "", "12", "", "19"} |
| Visual Basic | "42, 12, 19" | Char() = {","c, " "c}) | {"42", "", "12", "", "19"} |
| C# | "42..12..19." | new Char[] {'.'} | {"42", "", "12", "", "19", ""} |
| Visual Basic | "42..12..19." | Char() = {"." c} | {"42", "", "12", "", "19", ""} |
| C# | "Banana" | new Char[] {'.'} | {"Banana"} |
| Visual Basic | "Banana" | Char() = {"." c} | {"Banana"} |
| C# | "Darb\nSmarba" | new Char[] {} | {"Darb", "Smarba"} |
| Visual Basic | "Darb" & vbLf & "Smarba" | Char() = {} | {"Darb", "Smarba"} |
| C# | "Darb\nSmarba" | nullo | {"Darb", "Smarba"} |
| Visual Basic | "Darb" & vbLf & "Smarba" | Niente | {"Darb", "Smarba"} |
Matrice separatore
Ogni elemento del separatore definisce un delimitatore separato costituito da un singolo carattere.
Se l'argomento separator è null o non contiene caratteri, il metodo considera gli spazi vuoti come delimitatori. Gli spazi vuoti sono definiti dallo standard Unicode e il Char.IsWhiteSpace metodo restituisce true se viene passato un carattere di spazio vuoto.
String.Split(Char[]) e risoluzione dell'overload del compilatore
Anche se il singolo parametro per questo overload di è una matrice di String.Split caratteri, è possibile chiamarlo con un singolo carattere, come illustrato nell'esempio seguente.
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.
Poiché il separator parametro è decorato con l'attributo ParamArrayAttribute , i compilatori interpreteranno un singolo carattere come matrice di caratteri a singolo elemento. Questo non è il caso per altri String.Split overload che includono un separator parametro. È necessario passare in modo esplicito questi overload di una matrice di caratteri come separator argomento.
Dettagli confronto
Il Split(Char[]) metodo estrae le sottostringhe in questa stringa delimitate da uno o più caratteri nella separator matrice e restituisce tali sottostringhe come elementi di una matrice.
Il Split(Char[]) metodo cerca i delimitatori eseguendo confronti usando regole di ordinamento ordinale con distinzione tra maiuscole e minuscole. Per altre informazioni sugli ordinali di parole, stringhe e ordinali, vedere l'enumerazione System.Globalization.CompareOptions .
Considerazioni sulle prestazioni
I Split metodi allocano memoria per l'oggetto matrice restituito e un String oggetto per ogni elemento della matrice. Se l'applicazione richiede prestazioni ottimali o se la gestione dell'allocazione di memoria è fondamentale nell'applicazione, è consigliabile usare il IndexOf metodo o IndexOfAny . È anche possibile usare il Compare metodo per individuare una sottostringa all'interno di una stringa.
Per dividere una stringa in corrispondenza di un carattere separatore, utilizzare il IndexOf metodo o IndexOfAny per individuare un carattere separatore nella stringa. Per dividere una stringa in corrispondenza di una stringa separatore, utilizzare il IndexOf metodo o IndexOfAny per individuare il primo carattere della stringa separatore. Usare quindi il Compare metodo per determinare se i caratteri dopo il primo carattere sono uguali ai caratteri rimanenti della stringa separatore.
Inoltre, se lo stesso set di caratteri viene usato per suddividere le stringhe in più Split chiamate di metodo, è consigliabile creare una singola matrice e farvi riferimento in ogni chiamata al metodo. In questo modo si riduce significativamente il sovraccarico aggiuntivo di ogni chiamata al metodo.
Note per i chiamanti
In .NET Framework 3.5 e versioni precedenti, se il Split(Char[]) metodo viene passato a che separator è null o non contiene caratteri, il metodo usa un set leggermente diverso di caratteri di spazi vuoti per dividere la stringa rispetto Trim(Char[]) al metodo per tagliare la stringa. A partire da .NET Framework 4, entrambi i metodi usano un set identico di spazi vuoti Unicode.
Vedi anche
- Char
- Concat(Object)
- Insert(Int32, String)
- Join(String, String[])
- Remove(Int32, Int32)
- Replace(Char, Char)
- Substring(Int32)
- Trim(Char[])
Si applica a
Split(String, StringSplitOptions)
- Origine:
- String.Manipulation.cs
- Origine:
- String.Manipulation.cs
- Origine:
- String.Manipulation.cs
- Origine:
- String.Manipulation.cs
Suddivide una stringa in sottostringhe basate sul separatore di stringa specificato.
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()
Parametri
- separator
- String
Stringa che delimita le sottostringhe in questa stringa.
- options
- StringSplitOptions
Combinazione bit per bit dei valori di enumerazione che specifica se tagliare le sottostringhe e includere sottostringhe vuote.
Restituisce
Matrice i cui elementi contengono le sottostringhe di questa istanza delimitate da separator.