String.Split Metoda
Definice
Důležité
Některé informace platí pro předběžně vydaný produkt, který se může zásadně změnit, než ho výrobce nebo autor vydá. Microsoft neposkytuje žádné záruky, výslovné ani předpokládané, týkající se zde uváděných informací.
Vrátí pole řetězců obsahující podřetězce v této instanci, které jsou odděleny prvky zadaného řetězce nebo znakové pole Unicode.
Přetížení
Split(Char[]) |
Rozdělí řetězec na podřetězce na základě zadaných oddělovacích znaků. |
Split(Char, StringSplitOptions) |
Rozdělí řetězec na podřetězce na základě zadaného oddělovacího znaku a volitelně i možností. |
Split(Char[], Int32) |
Rozdělí řetězec na maximální počet podřetězců na základě zadaných oddělovacích znaků. |
Split(Char[], StringSplitOptions) |
Rozdělí řetězec na podřetězce na základě zadaných oddělovacích znaků a možností. |
Split(String, StringSplitOptions) |
Rozdělí řetězec na podřetězce založené na zadaném oddělovači řetězců. |
Split(String[], StringSplitOptions) |
Rozdělí řetězec na podřetězce na základě zadaného oddělovacího řetězce a volitelně i možností. |
Split(Char, Int32, StringSplitOptions) |
Rozdělí řetězec na maximální počet podřetězců na základě zadaného oddělovacího znaku a volitelně i možností. Rozdělí řetězec na maximální počet podřetězců na základě zadaného oddělovače znaků a volitelně vynechá prázdné podřetězce z výsledku. |
Split(Char[], Int32, StringSplitOptions) |
Rozdělí řetězec na maximální počet podřetězců na základě zadaných oddělovacích znaků a volitelně i možností. |
Split(String, Int32, StringSplitOptions) |
Rozdělí řetězec na maximální počet podřetězců na základě zadaného oddělovacího řetězce a volitelně i možností. |
Split(String[], Int32, StringSplitOptions) |
Rozdělí řetězec na maximální počet podřetězců na základě zadaných oddělovacích řetězců a volitelně i možností. |
Poznámky
Split se používá k rozdělení řetězce s oddělovači na podřetězce. K zadání nuly nebo více oddělovacích znaků nebo řetězců můžete použít pole znaků nebo řetězců. Pokud nejsou zadány žádné oddělovací znaky, řetězec se rozdělí na prázdné znaky.
Split Přetížení metody umožňuje omezit počet podřetězc vrácených metodou (Split(Char[], Int32)metoda), určit, zda se mají do výsledku zahrnout prázdné řetězce a/nebo oříznout podřetězce (Split(Char[], StringSplitOptions)metody aSplit(String[], StringSplitOptions)), nebo provést obojí (Split(Char[], Int32, StringSplitOptions)metody aSplit(String[], Int32, StringSplitOptions)).
Tip
Metoda Split není vždy nejlepším způsobem, jak rozdělit řetězec s oddělovači na podřetězce. Pokud nechcete extrahovat všechny podřetězce řetězce s oddělovači nebo pokud chcete analyzovat řetězec založený na vzoru místo sady oddělovačů, zvažte použití regulárních výrazů nebo zkombinujte jednu z metod vyhledávání, která vrací index znaku, s metodou Substring . Další informace najdete v tématu Extrakce podřetězcec z řetězce.
Příklad
Následující příklady ukazují tři různá přetížení .String.Split()
První příklad volá Split(Char[]) přetížení a předává jeden oddělovač.
string s = "You win some. You lose some.";
string[] subs = s.Split(' ');
foreach (var sub in subs)
{
Console.WriteLine($"Substring: {sub}");
}
// This example produces the following output:
//
// Substring: You
// Substring: win
// Substring: some.
// Substring: You
// Substring: lose
// Substring: some.
let s = "You win some. You lose some."
let subs = s.Split ' '
for sub in subs do
printfn $"Substring: {sub}"
// This example produces the following output:
//
// Substring: You
// Substring: win
// Substring: some.
// Substring: You
// Substring: lose
// Substring: some.
Dim s As String = "You win some. You lose some."
Dim subs As String() = s.Split()
For Each substring As String In subs
Console.WriteLine($"Substring: {substring}")
Next
' This example produces the following output:
'
' Substring: You
' Substring: win
' Substring: some.
' Substring: You
' Substring: lose
' Substring: some.
Jak vidíte, znaky tečky (.
) jsou zahrnuty ve dvou podřetěžcích. Pokud chcete znaky tečky vyloučit, můžete ho přidat jako další znak oddělovače. Další příklad ukazuje, jak to udělat.
string s = "You win some. You lose some.";
string[] subs = s.Split(' ', '.');
foreach (var sub in subs)
{
Console.WriteLine($"Substring: {sub}");
}
// This example produces the following output:
//
// Substring: You
// Substring: win
// Substring: some
// Substring:
// Substring: You
// Substring: lose
// Substring: some
// Substring:
let s = "You win some. You lose some."
let subs = s.Split(' ', '.')
for sub in subs do
printfn $"Substring: {sub}"
// This example produces the following output:
//
// Substring: You
// Substring: win
// Substring: some
// Substring:
// Substring: You
// Substring: lose
// Substring: some
// Substring:
Dim s As String = "You win some. You lose some."
Dim subs As String() = s.Split(" "c, "."c)
For Each substring As String In subs
Console.WriteLine($"Substring: {substring}")
Next
' This example produces the following output:
'
' Substring: You
' Substring: win
' Substring: some
' Substring:
' Substring: You
' Substring: lose
' Substring: some
' Substring:
Tečky jsou z podřetězdce pryč, ale teď byly zahrnuty další dva prázdné podřetězdce. Tyto prázdné podřetězdce představují podřetěžce mezi slovem a tečkou, která za ním následuje. Pokud chcete vynechat prázdné podřetězce z výsledného pole, můžete volat Split(Char[], StringSplitOptions) přetížení a zadat StringSplitOptions.RemoveEmptyEntries parametr options
.
string s = "You win some. You lose some.";
char[] separators = new char[] { ' ', '.' };
string[] subs = s.Split(separators, StringSplitOptions.RemoveEmptyEntries);
foreach (var sub in subs)
{
Console.WriteLine($"Substring: {sub}");
}
// This example produces the following output:
//
// Substring: You
// Substring: win
// Substring: some
// Substring: You
// Substring: lose
// Substring: some
let s = "You win some. You lose some."
let separators = [| ' '; '.' |]
let subs = s.Split(separators, StringSplitOptions.RemoveEmptyEntries)
for sub in subs do
printfn $"Substring: {sub}"
// This example produces the following output:
//
// Substring: You
// Substring: win
// Substring: some
// Substring: You
// Substring: lose
// Substring: some
Dim s As String = "You win some. You lose some."
Dim separators As Char() = New Char() {" "c, "."c}
Dim subs As String() = s.Split(separators, StringSplitOptions.RemoveEmptyEntries)
For Each substring As String In subs
Console.WriteLine($"Substring: {substring}")
Next
' This example produces the following output:
'
' Substring: You
' Substring: win
' Substring: some
' Substring: You
' Substring: lose
' Substring: some
Oddíly jednotlivých přetížení String.Split()
obsahují další příklady.
Split(Char[])
- Zdroj:
- String.Manipulation.cs
- Zdroj:
- String.Manipulation.cs
- Zdroj:
- String.Manipulation.cs
Rozdělí řetězec na podřetězce na základě zadaných oddělovacích znaků.
public:
cli::array <System::String ^> ^ Split(... cli::array <char> ^ separator);
public string[] Split (params char[] separator);
public string[] Split (params char[]? separator);
member this.Split : char[] -> string[]
Public Function Split (ParamArray separator As Char()) As String()
Parametry
- separator
- Char[]
Pole oddělovacích znaků, prázdné pole, které neobsahuje žádné oddělovače, nebo null
.
Návraty
Pole, jehož prvky obsahují podřetětěce z této instance oddělené jedním nebo více znaky v separator
. Další informace najdete v části Poznámky.
Příklady
Následující příklad ukazuje, jak extrahovat jednotlivá slova z bloku textu tím, že znak mezery (
) a znak tabulátoru (\t
) považuje za oddělovače. Řetězec, který se rozděluje, obsahuje oba tyto znaky.
string s = "Today\tI'm going to school";
string[] subs = s.Split(' ', '\t');
foreach (var sub in subs)
{
Console.WriteLine($"Substring: {sub}");
}
// This example produces the following output:
//
// Substring: Today
// Substring: I'm
// Substring: going
// Substring: to
// Substring: school
let s = "Today\tI'm going to school"
let subs = s.Split(' ', '\t')
for sub in subs do
printfn $"Substring: {sub}"
// This example produces the following output:
//
// Substring: Today
// Substring: I'm
// Substring: going
// Substring: to
// Substring: school
Dim s As String = "Today" & vbTab & "I'm going to school"
Dim subs As String() = s.Split(" "c, Char.Parse(vbTab))
For Each substring In subs
Console.WriteLine("Substring: " & substring)
Next
' This example produces the following output:
'
' Substring: Today
' Substring: I 'm
' Substring: going
' Substring: to
' Substring: school
Poznámky
Pokud je řetězec oddělený známou sadou znaků, můžete ho Split(Char[]) pomocí metody rozdělit do podřetězců.
Znaky oddělovače nejsou zahrnuty v prvcích vráceného pole. Pokud například pole oddělovače obsahuje znak "-" a hodnota instance aktuálního řetězce je "aa-bb-cc", vrátí metoda pole, které obsahuje tři prvky: "aa", "bb" a "cc".
Pokud tato instance neobsahuje žádné znaky v separator
, vrácené pole se skládá z jednoho prvku, který obsahuje tuto instanci.
Každý prvek definuje separator
samostatný znak oddělovače. Pokud jsou dva oddělovače vedle sebe nebo je nalezen oddělovač na začátku nebo na konci této instance, odpovídající prvek ve vráceném poli obsahuje Empty.
V následující tabulce jsou uvedeny některé příklady.
Jazyk | Řetězcová hodnota | Oddělovač | Vrácená matice |
---|---|---|---|
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# | "Banány" | new Char[] {'.'} | {"Banán"} |
Visual Basic | "Banány" | Char() = {"." c} | {"Banán"} |
C# | "Darb\nSmarba" | new Char[] {} | {"Darb", "Smarba"} |
Visual Basic | "Darb" & vbLf & "Smarba" | Char() = {} | {"Darb", "Smarba"} |
C# | "Darb\nSmarba" | null | {"Darb", "Smarba"} |
Visual Basic | "Darb" & vbLf & "Smarba" | Nothing | {"Darb", "Smarba"} |
Pole oddělovačů
Každý prvek oddělovače definuje samostatný oddělovač, který se skládá z jednoho znaku.
separator
Pokud argument je null
nebo neobsahuje žádné znaky, metoda považuje prázdné znaky za oddělovače. Prázdné znaky jsou definovány standardem Unicode a Char.IsWhiteSpace metoda vrátí true
, pokud je jí předán prázdný znak.
String.Split(Char[]) a překlad přetížení kompilátoru
I když jeden parametr pro toto přetížení String.Split je pole znaků, můžete jej volat s jedním znakem, jak je znázorněno v následujícím příkladu.
string value = "This is a short string.";
char delimiter = 's';
string[] substrings = value.Split(delimiter);
foreach (var substring in substrings)
Console.WriteLine(substring);
// The example displays the following output:
// Thi
// i
// a
// hort
// tring.
let value = "This is a short string."
let delimiter = 's'
let substrings = value.Split delimiter
for substring in substrings do
printfn $"{substring}"
// The example displays the following output:
// Thi
// i
// a
// hort
// tring.
Dim value As String = "This is a short string."
Dim delimiter As Char = "s"c
Dim substrings() As String = value.Split(delimiter)
For Each substring In substrings
Console.WriteLine(substring)
Next
End Sub
' The example displays the following output:
'
' Thi
' i
' a
' hort
' tring.
Vzhledem k tomu, že separator
parametr je opatřen atributem ParamArrayAttribute , kompilátory interpretují jeden znak jako pole znaků s jedním prvkem. Nejedná se o případ jiných String.Split přetížení, která obsahují separator
parametr; tato přetížení musíte explicitně předat pole znaků jako separator
argument.
Podrobnosti porovnání
Metoda Split(Char[]) extrahuje podřetězce v tomto řetězci, které jsou oddělené jedním nebo více znaky v separator
poli, a vrátí tyto podřetězce jako prvky pole.
Metoda Split(Char[]) hledá oddělovače provedením porovnání pomocí pravidel řazení s rozlišováním velkých a malých písmen. Další informace o řazení slov, řetězců a řadových řad naleznete ve výčtu System.Globalization.CompareOptions .
Otázky výkonu
Metody Split přidělují paměť pro vrácený objekt pole a String objekt pro každý prvek pole. Pokud vaše aplikace vyžaduje optimální výkon nebo pokud je správa přidělení paměti ve vaší aplikaci důležitá, zvažte použití IndexOf metody nebo IndexOfAny . Máte také možnost použít metodu Compare k vyhledání podřetězce v řetězci.
Chcete-li rozdělit řetězec na znak oddělovače, použijte metodu IndexOf nebo IndexOfAny k vyhledání znaku oddělovače v řetězci. Chcete-li rozdělit řetězec na řetězec oddělovače, použijte metodu IndexOf nebo IndexOfAny k vyhledání prvního znaku řetězce oddělovače. Pak pomocí Compare metody určete, jestli se znaky za tímto prvním znakem rovnají zbývajícím znakům řetězce oddělovače.
Kromě toho, pokud se stejná sada znaků používá k rozdělení řetězců ve více Split voláních metod, zvažte vytvoření jednoho pole a odkazování na něj v každém volání metody. To významně snižuje režii dalšího volání metody.
Poznámky pro volající
V rozhraní .NET Framework 3.5 a starších verzích, pokud Split(Char[]) je metoda předána separator
, která je null
nebo neobsahuje žádné znaky, metoda používá k rozdělení řetězce mírně odlišnou sadu prázdných znaků než Trim(Char[]) metoda pro oříznutí řetězce. Počínaje rozhraním .NET Framework 4 používají obě metody stejnou sadu prázdných znaků Unicode.
Viz také
- Char
- Concat(Object)
- Insert(Int32, String)
- Join(String, String[])
- Remove(Int32, Int32)
- Replace(Char, Char)
- Substring(Int32)
- Trim(Char[])
Platí pro
Split(Char, StringSplitOptions)
- Zdroj:
- String.Manipulation.cs
- Zdroj:
- String.Manipulation.cs
- Zdroj:
- String.Manipulation.cs
Rozdělí řetězec na podřetězce na základě zadaného oddělovacího znaku a volitelně i možností.
public string[] Split (char separator, StringSplitOptions options = System.StringSplitOptions.None);
member this.Split : char * StringSplitOptions -> string[]
Public Function Split (separator As Char, Optional options As StringSplitOptions = System.StringSplitOptions.None) As String()
Parametry
- separator
- Char
Znak, který definuje podřetězce v tomto řetězci.
- options
- StringSplitOptions
Bitová kombinace hodnot výčtu, která určuje, zda se mají oříznout podřetězce a zahrnout prázdné podřetězce.
Návraty
Pole, jehož prvky obsahují podřetětěce z této instance oddělené znakem separator
.
Platí pro
Split(Char[], Int32)
- Zdroj:
- String.Manipulation.cs
- Zdroj:
- String.Manipulation.cs
- Zdroj:
- String.Manipulation.cs
Rozdělí řetězec na maximální počet podřetězců na základě zadaných oddělovacích znaků.
public:
cli::array <System::String ^> ^ Split(cli::array <char> ^ separator, int count);
public string[] Split (char[] separator, int count);
public string[] Split (char[]? separator, int count);
member this.Split : char[] * int -> string[]
Public Function Split (separator As Char(), count As Integer) As String()
Parametry
- separator
- Char[]
Pole znaků, které odlišují podřetězce v tomto řetězci, prázdné pole, které neobsahuje žádné oddělovače, nebo null
.
- count
- Int32
Maximální počet podřetěžců, které se mají vrátit.
Návraty
Pole, jehož prvky obsahují podřetětěce v tomto případě oddělené jedním nebo více znaky v separator
. Další informace najdete v části Poznámky.
Výjimky
count
je negativní.
Příklady
Následující příklad ukazuje, jak count
lze použít k omezení počtu řetězců vrácených nástrojem 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(Nothing, 2)
Dim firstName As String = substrings(0)
Dim lastName As String
If substrings.Length > 1 Then
lastName = substrings(1)
End If
' If the user enters "Alex Johnson III":
' firstName = "Alex"
' lastName = "Johnson III"
Poznámky
Znaky oddělovače nejsou zahrnuty v prvcích vráceného pole.
Pokud tato instance neobsahuje žádné znaky v separator
, vrácené pole se skládá z jednoho prvku, který obsahuje tuto instanci. Pokud count
je nula, vrátí se prázdné pole.
separator
Pokud parametr je null
nebo neobsahuje žádné znaky, prázdné znaky se považují za oddělovače. Prázdné znaky jsou definovány standardem Unicode a Char.IsWhiteSpace metoda vrátí true
, pokud jsou předány.
Každý prvek definuje separator
samostatný znak oddělovače. Pokud jsou dva oddělovače sousedící nebo je nalezen oddělovač na začátku nebo konci této instance, odpovídající prvek pole obsahuje Empty.
Pokud je v tomto případě více než count
podřetětěce, první count - 1
podřetětěce jsou vráceny v prvních count - 1
prvcích návratové hodnoty a zbývající znaky v této instanci jsou vráceny v posledním prvku návratové hodnoty.
Pokud count
je větší než počet podřetězen, vrátí se dostupné podřetětěce a nevyvolá se žádná výjimka.
V následující tabulce jsou uvedeny některé příklady.
Jazyk | Řetězcová hodnota | Oddělovač | Vrácená matice |
---|---|---|---|
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# | "Banány" | new Char[] {'.'} | {"Banán"} |
Visual Basic | "Banány" | Char() = {"." c} | {"Banán"} |
C# | "Darb\nSmarba" | new Char[] {} | {"Darb", "Smarba"} |
Visual Basic | "Darb" & vbLf & "Smarba" | Char() = {} | {"Darb", "Smarba"} |
C# | "Darb\nSmarba" | null | {"Darb", "Smarba"} |
Visual Basic | "Darb" & vbLf & "Smarba" | Nothing | {"Darb", "Smarba"} |
Otázky výkonu
Metody Split přidělují paměť pro vrácený objekt pole a String objekt pro každý prvek pole. Pokud vaše aplikace vyžaduje optimální výkon nebo pokud je správa přidělení paměti pro vaši aplikaci důležitá, zvažte použití IndexOf metody nebo IndexOfAny a volitelně metody k vyhledání podřetězce Compare v řetězci.
Pokud rozdělujete řetězec na znak oddělovače, použijte metodu IndexOf nebo IndexOfAny k vyhledání znaku oddělovače v řetězci. Pokud rozdělujete řetězec na řetězec oddělovače, použijte metodu IndexOf nebo IndexOfAny k vyhledání prvního znaku řetězce oddělovače. Pak pomocí Compare metody určete, jestli se znaky za tímto prvním znakem rovnají zbývajícím znakům řetězce oddělovače.
Kromě toho, pokud se stejná sada znaků používá k rozdělení řetězců ve více Split voláních metod, zvažte vytvoření jednoho pole a odkazování na něj v každém volání metody. To významně snižuje režii dalšího volání metody.
Poznámky pro volající
V rozhraní .NET Framework 3.5 a starších verzích, pokud Split(Char[]) je metoda předána separator
, která je null
nebo neobsahuje žádné znaky, metoda používá k rozdělení řetězce mírně odlišnou sadu prázdných znaků než Trim(Char[]) metoda pro oříznutí řetězce. Počínaje rozhraním .NET Framework 4 používají obě metody stejnou sadu prázdných znaků Unicode.
Viz také
- Char
- Array
- Int32
- Concat(Object)
- Insert(Int32, String)
- Join(String, String[])
- Remove(Int32, Int32)
- Replace(Char, Char)
- Substring(Int32)
- Trim(Char[])
Platí pro
Split(Char[], StringSplitOptions)
- Zdroj:
- String.Manipulation.cs
- Zdroj:
- String.Manipulation.cs
- Zdroj:
- String.Manipulation.cs
Rozdělí řetězec na podřetězce na základě zadaných oddělovacích znaků a možností.
public:
cli::array <System::String ^> ^ Split(cli::array <char> ^ separator, StringSplitOptions options);
public string[] Split (char[] separator, StringSplitOptions options);
public string[] Split (char[]? separator, StringSplitOptions options);
[System.Runtime.InteropServices.ComVisible(false)]
public string[] Split (char[] separator, StringSplitOptions options);
member this.Split : char[] * StringSplitOptions -> string[]
[<System.Runtime.InteropServices.ComVisible(false)>]
member this.Split : char[] * StringSplitOptions -> string[]
Public Function Split (separator As Char(), options As StringSplitOptions) As String()
Parametry
- separator
- Char[]
Pole znaků, které odlišují podřetězce v tomto řetězci, prázdné pole, které neobsahuje žádné oddělovače, nebo null
.
- options
- StringSplitOptions
Bitová kombinace hodnot výčtu, která určuje, zda se mají oříznout podřetězce a zahrnout prázdné podřetězce.
Návraty
Pole, jehož prvky obsahují podřetězce v tomto řetězci oddělené jedním nebo více znaky v separator
. Další informace najdete v části Poznámky.
- Atributy
Výjimky
options
není jednou z StringSplitOptions hodnot.
Příklady
Následující příklad používá StringSplitOptions výčet k zahrnutí nebo vyloučení podřetězdců vygenerovaných metodou Split .
// This example demonstrates the String.Split(Char[], Boolean) and
// String.Split(Char[], Int32, Boolean) methods
using namespace System;
void Show( array<String^>^entries )
{
Console::WriteLine( "The return value contains these {0} elements:", entries->Length );
System::Collections::IEnumerator^ myEnum = entries->GetEnumerator();
while ( myEnum->MoveNext() )
{
String^ entry = safe_cast<String^>(myEnum->Current);
Console::Write( "<{0}>", entry );
}
Console::Write( "{0}{0}", Environment::NewLine );
}
int main()
{
String^ s = ",one,,,two,,,,,three,,";
array<Char>^sep = gcnew array<Char>{
','
};
array<String^>^result;
//
Console::WriteLine( "The original string is \"{0}\".", s );
Console::WriteLine( "The separation character is '{0}'.", sep[ 0 ] );
Console::WriteLine();
//
Console::WriteLine( "Split the string and return all elements:" );
result = s->Split( sep, StringSplitOptions::None );
Show( result );
//
Console::WriteLine( "Split the string and return all non-empty elements:" );
result = s->Split( sep, StringSplitOptions::RemoveEmptyEntries );
Show( result );
//
Console::WriteLine( "Split the string and return 2 elements:" );
result = s->Split( sep, 2, StringSplitOptions::None );
Show( result );
//
Console::WriteLine( "Split the string and return 2 non-empty elements:" );
result = s->Split( sep, 2, StringSplitOptions::RemoveEmptyEntries );
Show( result );
}
/*
This example produces the following results:
The original string is ",one,,,two,,,,,three,,".
The separation character is ','.
Split the string and return all elements:
The return value contains these 12 elements:
<><one><><><two><><><><><three><><>
Split the string and return all non-empty elements:
The return value contains these 3 elements:
<one><two><three>
Split the string and return 2 elements:
The return value contains these 2 elements:
<><one,,,two,,,,,three,,>
Split the string and return 2 non-empty elements:
The return value contains these 2 elements:
<one><,,two,,,,,three,,>
*/
// This example demonstrates the String.Split() methods that use
// the StringSplitOptions enumeration.
string s1 = ",ONE,,TWO,,,THREE,,";
string s2 = "[stop]" +
"ONE[stop][stop]" +
"TWO[stop][stop][stop]" +
"THREE[stop][stop]";
char[] charSeparators = new char[] { ',' };
string[] stringSeparators = new string[] { "[stop]" };
string[] result;
// ------------------------------------------------------------------------------
// Split a string delimited by characters.
// ------------------------------------------------------------------------------
Console.WriteLine("1) Split a string delimited by characters:\n");
// Display the original string and delimiter characters.
Console.WriteLine($"1a) The original string is \"{s1}\".");
Console.WriteLine($"The delimiter character is '{charSeparators[0]}'.\n");
// Split a string delimited by characters and return all elements.
Console.WriteLine("1b) Split a string delimited by characters and " +
"return all elements:");
result = s1.Split(charSeparators, StringSplitOptions.None);
Show(result);
// Split a string delimited by characters and return all non-empty elements.
Console.WriteLine("1c) Split a string delimited by characters and " +
"return all non-empty elements:");
result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// Split the original string into the string and empty string before the
// delimiter and the remainder of the original string after the delimiter.
Console.WriteLine("1d) Split a string delimited by characters and " +
"return 2 elements:");
result = s1.Split(charSeparators, 2, StringSplitOptions.None);
Show(result);
// Split the original string into the string after the delimiter and the
// remainder of the original string after the delimiter.
Console.WriteLine("1e) Split a string delimited by characters and " +
"return 2 non-empty elements:");
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// ------------------------------------------------------------------------------
// Split a string delimited by another string.
// ------------------------------------------------------------------------------
Console.WriteLine("2) Split a string delimited by another string:\n");
// Display the original string and delimiter string.
Console.WriteLine($"2a) The original string is \"{s2}\".");
Console.WriteLine($"The delimiter string is \"{stringSeparators[0]}\".\n");
// Split a string delimited by another string and return all elements.
Console.WriteLine("2b) Split a string delimited by another string and " +
"return all elements:");
result = s2.Split(stringSeparators, StringSplitOptions.None);
Show(result);
// Split the original string at the delimiter and return all non-empty elements.
Console.WriteLine("2c) Split a string delimited by another string and " +
"return all non-empty elements:");
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// Split the original string into the empty string before the
// delimiter and the remainder of the original string after the delimiter.
Console.WriteLine("2d) Split a string delimited by another string and " +
"return 2 elements:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.None);
Show(result);
// Split the original string into the string after the delimiter and the
// remainder of the original string after the delimiter.
Console.WriteLine("2e) Split a string delimited by another string and " +
"return 2 non-empty elements:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// Display the array of separated strings using a local function
void Show(string[] entries)
{
Console.WriteLine($"The return value contains these {entries.Length} elements:");
foreach (string entry in entries)
{
Console.Write($"<{entry}>");
}
Console.Write("\n\n");
}
/*
This example produces the following results:
1) Split a string delimited by characters:
1a) The original string is ",ONE,,TWO,,,THREE,,".
The delimiter character is ','.
1b) Split a string delimited by characters and return all elements:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>
1c) Split a string delimited by characters and return all non-empty elements:
The return value contains these 3 elements:
<ONE><TWO><THREE>
1d) Split a string delimited by characters and return 2 elements:
The return value contains these 2 elements:
<><ONE,,TWO,,,THREE,,>
1e) Split a string delimited by characters and return 2 non-empty elements:
The return value contains these 2 elements:
<ONE><TWO,,,THREE,,>
2) Split a string delimited by another string:
2a) The original string is "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".
The delimiter string is "[stop]".
2b) Split a string delimited by another string and return all elements:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>
2c) Split a string delimited by another string and return all non-empty elements:
The return value contains these 3 elements:
<ONE><TWO><THREE>
2d) Split a string delimited by another string and return 2 elements:
The return value contains these 2 elements:
<><ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]>
2e) Split a string delimited by another string and return 2 non-empty elements:
The return value contains these 2 elements:
<ONE><TWO[stop][stop][stop]THREE[stop][stop]>
*/
// 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"
let s1 = ",ONE,,TWO,,,THREE,,"
let s2 = "[stop]" +
"ONE[stop][stop]" +
"TWO[stop][stop][stop]" +
"THREE[stop][stop]"
let charSeparators = [| ',' |]
let stringSeparators = [| "[stop]" |]
// ------------------------------------------------------------------------------
// Split a string delimited by characters.
// ------------------------------------------------------------------------------
printfn "1) Split a string delimited by characters:\n"
// Display the original string and delimiter characters.
printfn $"1a) The original string is \"{s1}\"."
printfn $"The delimiter character is '{charSeparators[0]}'.\n"
// Split a string delimited by characters and return all elements.
printfn "1b) Split a string delimited by characters and return all elements:"
let result = s1.Split(charSeparators, StringSplitOptions.None)
show result
// Split a string delimited by characters and return all non-empty elements.
printfn "1c) Split a string delimited by characters and return all non-empty elements:"
let result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries)
show result
// Split the original string into the string and empty string before the
// delimiter and the remainder of the original string after the delimiter.
printfn "1d) Split a string delimited by characters and return 2 elements:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.None)
show result
// Split the original string into the string after the delimiter and the
// remainder of the original string after the delimiter.
printfn "1e) Split a string delimited by characters and return 2 non-empty elements:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
show result
// ------------------------------------------------------------------------------
// Split a string delimited by another string.
// ------------------------------------------------------------------------------
printfn "2) Split a string delimited by another string:\n"
// Display the original string and delimiter string.
printfn $"2a) The original string is \"{s2}\"."
printfn $"The delimiter string is \"{stringSeparators[0]}\".\n"
// Split a string delimited by another string and return all elements.
printfn "2b) Split a string delimited by another string and return all elements:"
let result = s2.Split(stringSeparators, StringSplitOptions.None)
show result
// Split the original string at the delimiter and return all non-empty elements.
printfn "2c) Split a string delimited by another string and return all non-empty elements:"
let result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)
show result
// Split the original string into the empty string before the
// delimiter and the remainder of the original string after the delimiter.
printfn "2d) Split a string delimited by another string and return 2 elements:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.None)
show result
// Split the original string into the string after the delimiter and the
// remainder of the original string after the delimiter.
printfn "2e) Split a string delimited by another string and return 2 non-empty elements:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
show result
(*
This example produces the following results:
1) Split a string delimited by characters:
1a) The original string is ",ONE,,TWO,,,THREE,,".
The delimiter character is ','.
1b) Split a string delimited by characters and return all elements:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>
1c) Split a string delimited by characters and return all non-empty elements:
The return value contains these 3 elements:
<ONE><TWO><THREE>
1d) Split a string delimited by characters and return 2 elements:
The return value contains these 2 elements:
<><ONE,,TWO,,,THREE,,>
1e) Split a string delimited by characters and return 2 non-empty elements:
The return value contains these 2 elements:
<ONE><TWO,,,THREE,,>
2) Split a string delimited by another string:
2a) The original string is "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".
The delimiter string is "[stop]".
2b) Split a string delimited by another string and return all elements:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>
2c) Split a string delimited by another string and return all non-empty elements:
The return value contains these 3 elements:
<ONE><TWO><THREE>
2d) Split a string delimited by another string and return 2 elements:
The return value contains these 2 elements:
<><ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]>
2e) Split a string delimited by another string and return 2 non-empty elements:
The return value contains these 2 elements:
<ONE><TWO[stop][stop][stop]THREE[stop][stop]>
*)
Dim s1 As String = ",ONE,,TWO,,,THREE,,"
Dim s2 As String = "[stop]" &
"ONE[stop][stop]" &
"TWO[stop][stop][stop]" &
"THREE[stop][stop]"
Dim charSeparators() As Char = {","c}
Dim stringSeparators() As String = {"[stop]"}
Dim result() As String
' ------------------------------------------------------------------------------
' Split a string delimited by characters.
' ------------------------------------------------------------------------------
Console.WriteLine("1) Split a string delimited by characters:" & vbCrLf)
' Display the original string and delimiter characters.
Console.WriteLine("1a) The original string is ""{0}"".", s1)
Console.WriteLine("The delimiter character is '{0}'." & vbCrLf, charSeparators(0))
' Split a string delimited by characters and return all elements.
Console.WriteLine("1b) Split a string delimited by characters and " &
"return all elements:")
result = s1.Split(charSeparators, StringSplitOptions.None)
Show(result)
' Split a string delimited by characters and return all non-empty elements.
Console.WriteLine("1c) Split a string delimited by characters and " &
"return all non-empty elements:")
result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries)
Show(result)
' Split the original string into the string and empty string before the
' delimiter and the remainder of the original string after the delimiter.
Console.WriteLine("1d) Split a string delimited by characters and " &
"return 2 elements:")
result = s1.Split(charSeparators, 2, StringSplitOptions.None)
Show(result)
' Split the original string into the string after the delimiter and the
' remainder of the original string after the delimiter.
Console.WriteLine("1e) Split a string delimited by characters and " &
"return 2 non-empty elements:")
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
Show(result)
' ------------------------------------------------------------------------------
' Split a string delimited by another string.
' ------------------------------------------------------------------------------
Console.WriteLine("2) Split a string delimited by another string:" & vbCrLf)
' Display the original string and delimiter string.
Console.WriteLine("2a) The original string is ""{0}"".", s2)
Console.WriteLine("The delimiter string is ""{0}""." & vbCrLf, stringSeparators(0))
' Split a string delimited by another string and return all elements.
Console.WriteLine("2b) Split a string delimited by another string and " &
"return all elements:")
result = s2.Split(stringSeparators, StringSplitOptions.None)
Show(result)
' Split the original string at the delimiter and return all non-empty elements.
Console.WriteLine("2c) Split a string delimited by another string and " &
"return all non-empty elements:")
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)
Show(result)
' Split the original string into the empty string before the
' delimiter and the remainder of the original string after the delimiter.
Console.WriteLine("2d) Split a string delimited by another string and " &
"return 2 elements:")
result = s2.Split(stringSeparators, 2, StringSplitOptions.None)
Show(result)
' Split the original string into the string after the delimiter and the
' remainder of the original string after the delimiter.
Console.WriteLine("2e) Split a string delimited by another string and " &
"return 2 non-empty elements:")
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
Show(result)
End Sub
' Display the array of separated strings.
Public Shared Sub Show(ByVal entries() As String)
Console.WriteLine("The return value contains these {0} elements:", entries.Length)
Dim entry As String
For Each entry In entries
Console.Write("<{0}>", entry)
Next entry
Console.Write(vbCrLf & vbCrLf)
End Sub
'This example produces the following results:
'
'1) Split a string delimited by characters:
'
'1a) The original string is ",ONE,,TWO,,,THREE,,".
'The delimiter character is ','.
'
'1b) Split a string delimited by characters and return all elements:
'The return value contains these 9 elements:
'<><ONE><><TWO><><><THREE><><>
'
'1c) Split a string delimited by characters and return all non-empty elements:
'The return value contains these 3 elements:
'<ONE><TWO><THREE>
'
'1d) Split a string delimited by characters and return 2 elements:
'The return value contains these 2 elements:
'<><ONE,,TWO,,,THREE,,>
'
'1e) Split a string delimited by characters and return 2 non-empty elements:
'The return value contains these 2 elements:
'<ONE><TWO,,,THREE,,>
'
'2) Split a string delimited by another string:
'
'2a) The original string is "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".
'The delimiter string is "[stop]".
'
'2b) Split a string delimited by another string and return all elements:
'The return value contains these 9 elements:
'<><ONE><><TWO><><><THREE><><>
'
'2c) Split a string delimited by another string and return all non-empty elements:
'The return value contains these 3 elements:
'<ONE><TWO><THREE>
'
'2d) Split a string delimited by another string and return 2 elements:
'The return value contains these 2 elements:
'<><ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]>
'
'2e) Split a string delimited by another string and return 2 non-empty elements:
'The return value contains these 2 elements:
'<ONE><TWO[stop][stop][stop]THREE[stop][stop]>
'
Poznámky
Znaky oddělovače (znaky v separator
poli) nejsou zahrnuty do prvků vráceného pole. Pokud například separator
pole obsahuje znak "-" a hodnota instance aktuálního řetězce je "aa-bb-cc", vrátí metoda pole, které obsahuje tři prvky: "aa", "bb" a "cc".
Pokud tato instance neobsahuje žádné znaky v separator
, vrácené pole se skládá z jednoho prvku, který obsahuje tuto instanci.
options
Pokud parametr je RemoveEmptyEntries a délka této instance je nula, vrátí metoda prázdné pole.
Každý prvek definuje separator
samostatný oddělovač, který se skládá z jednoho znaku. options
Pokud je Noneargument a dva oddělovače sousedí nebo je nalezen oddělovač na začátku nebo na konci této instance, odpovídající prvek pole obsahuje String.Empty. Pokud například separator
obsahuje dva elementy, '-'
a '_'
, hodnota instance řetězce je "-_aa-_" a hodnota argumentu options
je None, metoda vrátí pole řetězců s následujícími pěti prvky:
String.Empty, který představuje prázdný řetězec, který předchází znaku "-" v indexu 0.
String.Empty, který představuje prázdný řetězec mezi znakem "-" v indexu 0 a znakem _v indexu 1.
"aa".
String.Empty, který představuje prázdný řetězec, který následuje za znakem "-" v indexu 4.
String.Empty, který představuje prázdný řetězec, který následuje za znakem _v indexu 5.
Pole oddělovačů
separator
Pokud parametr je null
nebo neobsahuje žádné znaky, předpokládá se, že oddělovačem jsou prázdné znaky. Prázdné znaky jsou definovány standardem Unicode a Char.IsWhiteSpace metoda vrátí true
, pokud jsou do ní předány.
null
char[] separator
Pokud chcete předat parametr, musíte označit typ parametrunull
, který má určit nejednoznačnost volání z některých jiných přetížení, například Split(String[], StringSplitOptions). Následující příklad ukazuje několik způsobů k jednoznačné identifikaci tohoto přetížení.
string phrase = "The quick brown fox";
_ = phrase.Split(default(char[]), StringSplitOptions.RemoveEmptyEntries);
_ = phrase.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries);
_ = phrase.Split(null as char[], StringSplitOptions.RemoveEmptyEntries);
let phrase = "The quick brown fox"
phrase.Split(Unchecked.defaultof<char[]>, StringSplitOptions.RemoveEmptyEntries) |> ignore
phrase.Split(null :> char[], StringSplitOptions.RemoveEmptyEntries) |> ignore
phrase.Split((null: char[]), StringSplitOptions.RemoveEmptyEntries) |> ignore
Dim phrase As String = "The quick brown fox"
Dim words() As String
words = phrase.Split(TryCast(Nothing, Char()),
StringSplitOptions.RemoveEmptyEntries)
words = phrase.Split(New Char() {},
StringSplitOptions.RemoveEmptyEntries)
Podrobnosti o porovnání
Metoda Split extrahuje podřetězce v tomto řetězci, které jsou oddělené jedním nebo více znaky v parametru separator
, a vrátí tyto podřetězcece jako prvky pole.
Metoda Split hledá oddělovače provedením porovnání s použitím pravidel řazení řad rozlišujících velká a malá písmena. Další informace o řazení slov, řetězců a řadových řad najdete ve výčtu System.Globalization.CompareOptions .
Otázky výkonu
Metody Split přidělují paměť pro vrácený objekt pole a String objekt pro každý prvek pole. Pokud vaše aplikace vyžaduje optimální výkon nebo pokud je správa přidělení paměti ve vaší aplikaci kritická, zvažte použití IndexOf metody nebo IndexOfAny a volitelně metody k vyhledání podřetězce Compare v řetězci.
Pokud rozdělujete řetězec na znak oddělovače, použijte metodu IndexOf nebo IndexOfAny k vyhledání znaku oddělovače v řetězci. Pokud rozdělujete řetězec na řetězec oddělovače, použijte metodu IndexOf nebo IndexOfAny k vyhledání prvního znaku oddělovače řetězce. Pak pomocí Compare metody určete, zda se znaky za tímto prvním znakem rovnají zbývajícím znakům řetězce oddělovače.
Pokud se navíc stejná sada znaků používá k rozdělení řetězců ve více Split voláních metod, zvažte vytvoření jednoho pole a odkazování na ni v každém volání metody. To významně snižuje režii dalšího volání metody.
Poznámky pro volající
V rozhraní .NET Framework 3.5 a starších verzích, pokud Split(Char[]) je metoda předána separator
, která je null
nebo neobsahuje žádné znaky, metoda používá k rozdělení řetězce mírně odlišnou sadu prázdných znaků než Trim(Char[]) metoda pro oříznutí řetězce. Počínaje rozhraním .NET Framework 4 používají obě metody stejnou sadu prázdných znaků Unicode.
Platí pro
Split(String, StringSplitOptions)
- Zdroj:
- String.Manipulation.cs
- Zdroj:
- String.Manipulation.cs
- Zdroj:
- String.Manipulation.cs
Rozdělí řetězec na podřetězce, které jsou založené na zadaném oddělovači řetězců.
public string[] Split (string? separator, StringSplitOptions options = System.StringSplitOptions.None);
public string[] Split (string separator, StringSplitOptions options = System.StringSplitOptions.None);
member this.Split : string * StringSplitOptions -> string[]
Public Function Split (separator As String, Optional options As StringSplitOptions = System.StringSplitOptions.None) As String()
Parametry
- separator
- String
Řetězec, který odděluje podřetězce v tomto řetězci.
- options
- StringSplitOptions
Bitové kombinace hodnot výčtu, která určuje, zda se mají oříznout podřetězce a zahrnout prázdné podřetězcece.
Návraty
Pole, jehož prvky obsahují podřetětce z této instance, které jsou oddělené znakem separator
.
Platí pro
Split(String[], StringSplitOptions)
- Zdroj:
- String.Manipulation.cs
- Zdroj:
- String.Manipulation.cs
- Zdroj:
- String.Manipulation.cs
Rozdělí řetězec na podřetězce na základě zadaného řetězce oddělovače a volitelně i možností.
public:
cli::array <System::String ^> ^ Split(cli::array <System::String ^> ^ separator, StringSplitOptions options);
public string[] Split (string[] separator, StringSplitOptions options);
public string[] Split (string[]? separator, StringSplitOptions options);
[System.Runtime.InteropServices.ComVisible(false)]
public string[] Split (string[] separator, StringSplitOptions options);
member this.Split : string[] * StringSplitOptions -> string[]
[<System.Runtime.InteropServices.ComVisible(false)>]
member this.Split : string[] * StringSplitOptions -> string[]
Public Function Split (separator As String(), options As StringSplitOptions) As String()
Parametry
- separator
- String[]
Pole řetězců, které odlišují podřetězce v tomto řetězci, prázdné pole, které neobsahuje žádné oddělovače, nebo null
.
- options
- StringSplitOptions
Bitové kombinace hodnot výčtu, která určuje, zda se mají oříznout podřetězce a zahrnout prázdné podřetězcece.
Návraty
Pole, jehož prvky obsahují podřetězce v tomto řetězci, které jsou oddělené jedním nebo více řetězci v separator
. Další informace najdete v části Poznámky.
- Atributy
Výjimky
options
není jednou z StringSplitOptions hodnot.
Příklady
Následující příklad znázorňuje rozdíl v polích vrácených voláním metody řetězce String.Split(String[], StringSplitOptions) s jejím options
parametrem se rovná StringSplitOptions.None a StringSplitOptions.RemoveEmptyEntries.
string source = "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]";
string[] stringSeparators = new string[] { "[stop]" };
string[] result;
// Display the original string and delimiter string.
Console.WriteLine($"Splitting the string:\n \"{source}\".");
Console.WriteLine();
Console.WriteLine($"Using the delimiter string:\n \"{stringSeparators[0]}\"");
Console.WriteLine();
// Split a string delimited by another string and return all elements.
result = source.Split(stringSeparators, StringSplitOptions.None);
Console.WriteLine($"Result including all elements ({result.Length} elements):");
Console.Write(" ");
foreach (string s in result)
{
Console.Write("'{0}' ", String.IsNullOrEmpty(s) ? "<>" : s);
}
Console.WriteLine();
Console.WriteLine();
// Split delimited by another string and return all non-empty elements.
result = source.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);
Console.WriteLine($"Result including non-empty elements ({result.Length} elements):");
Console.Write(" ");
foreach (string s in result)
{
Console.Write("'{0}' ", String.IsNullOrEmpty(s) ? "<>" : s);
}
Console.WriteLine();
// The example displays the following output:
// Splitting the string:
// "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".
//
// Using the delimiter string:
// "[stop]"
//
// Result including all elements (9 elements):
// '<>' 'ONE' '<>' 'TWO' '<>' '<>' 'THREE' '<>' '<>'
//
// Result including non-empty elements (3 elements):
// 'ONE' 'TWO' 'THREE'
let source = "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]"
let stringSeparators = [| "[stop]" |]
// Display the original string and delimiter string.
printfn $"Splitting the string:\n \"{source}\".\n"
printfn $"Using the delimiter string:\n \"{stringSeparators[0]}\"\n"
// Split a string delimited by another string and return all elements.
let result = source.Split(stringSeparators, StringSplitOptions.None)
printfn $"Result including all elements ({result.Length} elements):"
printf " "
for s in result do
printf $"""'{if String.IsNullOrEmpty s then "<>" else s}' """
printfn "\n"
// Split delimited by another string and return all non-empty elements.
let result = source.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)
Console.WriteLine($"Result including non-empty elements ({result.Length} elements):")
printf " "
for s in result do
printf $"""'{if String.IsNullOrEmpty s then "<>" else s}' """
printfn ""
// The example displays the following output:
// Splitting the string:
// "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".
//
// Using the delimiter string:
// "[stop]"
//
// let result including all elements (9 elements):
// '<>' 'ONE' '<>' 'TWO' '<>' '<>' 'THREE' '<>' '<>'
//
// let result including non-empty elements (3 elements):
// 'ONE' 'TWO' 'THREE'
Dim source As String = "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]"
Dim stringSeparators() As String = {"[stop]"}
Dim result() As String
' Display the original string and delimiter string.
Console.WriteLine("Splitting the string:{0} '{1}'.", vbCrLf, source)
Console.WriteLine()
Console.WriteLine("Using the delimiter string:{0} '{1}'.",
vbCrLf, stringSeparators(0))
Console.WriteLine()
' Split a string delimited by another string and return all elements.
result = source.Split(stringSeparators, StringSplitOptions.None)
Console.WriteLine("Result including all elements ({0} elements):",
result.Length)
Console.Write(" ")
For Each s As String In result
Console.Write("'{0}' ", IIf(String.IsNullOrEmpty(s), "<>", s))
Next
Console.WriteLine()
Console.WriteLine()
' Split delimited by another string and return all non-empty elements.
result = source.Split(stringSeparators,
StringSplitOptions.RemoveEmptyEntries)
Console.WriteLine("Result including non-empty elements ({0} elements):",
result.Length)
Console.Write(" ")
For Each s As String In result
Console.Write("'{0}' ", IIf(String.IsNullOrEmpty(s), "<>", s))
Next
Console.WriteLine()
' The example displays the following output:
' Splitting the string:
' "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".
'
' Using the delimiter string:
' "[stop]"
'
' Result including all elements (9 elements):
' '<>' 'ONE' '<>' 'TWO' '<>' '<>' 'THREE' '<>' '<>'
'
' Result including non-empty elements (3 elements):
' 'ONE' 'TWO' 'THREE'
Následující příklad definuje pole oddělovačů, které obsahují interpunkční znamény a prázdné znaky. Předání tohoto pole spolu s hodnotou StringSplitOptions.RemoveEmptyEntriesSplit(String[], StringSplitOptions) do metody vrátí pole, které se skládá z jednotlivých slov z řetězce.
string[] separators = { ",", ".", "!", "?", ";", ":", " " };
string value = "The handsome, energetic, young dog was playing with his smaller, more lethargic litter mate.";
string[] words = value.Split(separators, StringSplitOptions.RemoveEmptyEntries);
foreach (var word in words)
Console.WriteLine(word);
// The example displays the following output:
// The
// handsome
// energetic
// young
// dog
// was
// playing
// with
// his
// smaller
// more
// lethargic
// litter
// mate
let separators = [| ","; "."; "!"; "?"; ""; ":"; " " |]
let value = "The handsome, energetic, young dog was playing with his smaller, more lethargic litter mate."
let words = value.Split(separators, StringSplitOptions.RemoveEmptyEntries)
for word in words do
printfn $"${word}"
// The example displays the following output:
// The
// handsome
// energetic
// young
// dog
// was
// playing
// with
// his
// smaller
// more
// lethargic
// litter
// mate
Dim separators() As String = {",", ".", "!", "?", ";", ":", " "}
Dim value As String = "The handsome, energetic, young dog was playing with his smaller, more lethargic litter mate."
Dim words() As String = value.Split(separators, StringSplitOptions.RemoveEmptyEntries)
For Each word In words
Console.WriteLine(word)
Next
End Sub
' The example displays the following output:
'
' The
' handsome
' energetic
' young
' dog
' was
' playing
' with
' his
' smaller
' more
' lethargic
' litter
' mate
Všimněte si, že metoda je volána s argumentem nastaveným options
na StringSplitOptions.RemoveEmptyEntries. Tím zabráníte vráceným polím v zahrnutí String.Empty hodnot, které představují prázdné shody podřetězdce mezi interpunkčními znaménkami a prázdnými znaky.
Poznámky
Pokud je řetězec oddělený známou sadou řetězců, můžete použít metodu Split k jeho oddělení na podřetězce.
Řetězce oddělovače nejsou zahrnuty v prvcích vráceného pole. Pokud například separator
pole obsahuje řetězec "--" a hodnota aktuální instance řetězce je "aa--bb--cc", vrátí metoda pole, které obsahuje tři prvky: "aa", "bb" a "cc".
Pokud tato instance neobsahuje žádný z řetězců v separator
, vrácené pole se skládá z jednoho prvku, který obsahuje tuto instanci.
options
Pokud je RemoveEmptyEntries parametr a délka této instance je nula, vrátí metoda prázdné pole.
Každý prvek definuje separator
samostatný oddělovač, který se skládá z jednoho nebo více znaků. options
Pokud je Noneargument , a dva oddělovače jsou sousedící nebo oddělovač je nalezen na začátku nebo na konci této instance, odpovídající prvek matice obsahuje String.Empty. Pokud separator
například obsahuje dva prvky , -" a "_", hodnota instance řetězce je "-_aa-_" a hodnota argumentu options
je None, vrátí metoda pole řetězců s následujícími pěti prvky:
String.Empty, který představuje prázdný řetězec, který předchází podřetězci "-" v indexu 0.
String.Empty, který představuje prázdný řetězec mezi podřetězcec "-" v indexu 0 a podřetězcec "_" v indexu 1.
"aa".
String.Empty, který představuje prázdný řetězec, který následuje za podřetězcem "-" v indexu 4.
String.Empty, který představuje prázdný řetězec, který následuje za podřetězcem _v indexu 5.
Pole oddělovače
Pokud se některý z prvků v separator
souboru skládá z více znaků, považuje se celý podřetězen za oddělovač. Pokud je například jeden z prvků v separator
souboru "10", při pokusu o rozdělení řetězce "This10s10a10string" vrátí následující pole se čtyřmi prvky: { "This", "is", "a", "string". }.
separator
Pokud parametr je null
nebo neobsahuje žádné neprázdné řetězce, znaky prázdných znaků se považují za oddělovače. Prázdné znaky jsou definovány standardem Unicode a Char.IsWhiteSpace metoda vrátí true
, pokud jsou do ní předány.
null
string[] separator
Pokud chcete předat parametr, musíte označit typ parametrunull
, který má určit nejednoznačnost volání z některých jiných přetížení, například Split(Char[], StringSplitOptions). Následující příklad ukazuje několik způsobů k jednoznačné identifikaci tohoto přetížení.
string phrase = "The quick brown fox";
_ = phrase.Split(default(string[]), StringSplitOptions.RemoveEmptyEntries);
_ = phrase.Split((string[]?)null, StringSplitOptions.RemoveEmptyEntries);
_ = phrase.Split(null as string[], StringSplitOptions.RemoveEmptyEntries);
let phrase = "The quick brown fox"
phrase.Split(Unchecked.defaultof<string[]>, StringSplitOptions.RemoveEmptyEntries) |> ignore
phrase.Split(null :> string[], StringSplitOptions.RemoveEmptyEntries) |> ignore
phrase.Split((null: string[]), StringSplitOptions.RemoveEmptyEntries) |> ignore
Dim phrase As String = "The quick brown fox"
Dim words() As String
words = phrase.Split(TryCast(Nothing, String()),
StringSplitOptions.RemoveEmptyEntries)
words = phrase.Split(New String() {},
StringSplitOptions.RemoveEmptyEntries)
Podrobnosti o porovnání
Metoda Split extrahuje podřetězce v tomto řetězci, které jsou oddělené jedním nebo více řetězci v parametru separator
, a vrátí tyto podřetězcece jako prvky pole.
Metoda Split hledá oddělovače provedením porovnání s použitím pravidel řazení řad rozlišujících velká a malá písmena. Další informace o řazení slov, řetězců a řadových řad najdete ve výčtu System.Globalization.CompareOptions .
Metoda Split ignoruje jakýkoli prvek, separator
jehož hodnota je null
nebo prázdný řetězec ("").
Aby se zabránilo nejednoznačným výsledkům, když řetězce v separator
souboru mají společné znaky, Split operace pokračuje od začátku do konce hodnoty instance a odpovídá prvnímu prvku v separator
instanci, který je roven oddělovači v instanci. Pořadí, ve kterém jsou v instanci nalezeny podřetětěce, má přednost před pořadím prvků v separator
.
Představte si například instanci, jejíž hodnota je "abcdef". Pokud byl první prvek v separator
souboru "ef" a druhý prvek byl "bcde", výsledkem operace rozdělení by bylo pole řetězců, které obsahuje dva elementy: "a" a "f". Je to proto, že je nalezen podřetěžce v instanci "bcde" a odpovídá elementu v separator
před podřetěžce "f".
Pokud byl první prvek separator
"bcd" a druhý prvek byl "bc", výsledkem operace rozdělení by bylo pole řetězců, které obsahuje dva prvky, "a" a "ef". Je to proto, že "bcd" je první oddělovač, separator
který odpovídá oddělovači v instanci. Pokud bylo pořadí oddělovačů obráceno tak, že první prvek byl "bc" a druhý prvek byl "bcd", výsledkem by bylo pole řetězců, které obsahuje dva prvky, "a" a "def".
Otázky výkonu
Metody Split přidělují paměť pro vrácený objekt pole a String objekt pro každý prvek pole. Pokud vaše aplikace vyžaduje optimální výkon nebo pokud je správa přidělení paměti ve vaší aplikaci kritická, zvažte použití IndexOf metody nebo IndexOfAny a volitelně metody k vyhledání podřetězce Compare v řetězci.
Pokud rozdělujete řetězec na znak oddělovače, použijte metodu IndexOf nebo IndexOfAny k vyhledání znaku oddělovače v řetězci. Pokud rozdělujete řetězec na řetězec oddělovače, použijte metodu IndexOf nebo IndexOfAny k vyhledání prvního znaku oddělovače řetězce. Pak pomocí Compare metody určete, zda se znaky za tímto prvním znakem rovnají zbývajícím znakům řetězce oddělovače.
Pokud se navíc stejná sada znaků používá k rozdělení řetězců ve více Split voláních metod, zvažte vytvoření jednoho pole a odkazování na ni v každém volání metody. To významně snižuje režii dalšího volání metody.
Poznámky pro volající
V rozhraní .NET Framework 3.5 a starších verzích, pokud Split(Char[]) je metoda předána separator
null
nebo neobsahuje žádné znaky, metoda používá mírně odlišnou sadu prázdných znaků rozdělit řetězec než Trim(Char[]) metoda oříznout řetězec. Počínaje rozhraním .NET Framework 4 používají obě metody identickou sadu prázdných znaků unicode.
Platí pro
Split(Char, Int32, StringSplitOptions)
- Zdroj:
- String.Manipulation.cs
- Zdroj:
- String.Manipulation.cs
- Zdroj:
- String.Manipulation.cs
Rozdělí řetězec na maximální počet podřetězc na základě zadaného znaku oddělovače a volitelně i možností. Rozdělí řetězec na maximální počet podřetězc na základě zadaného oddělovače znaků a volitelně vynechá prázdné podřetězcece z výsledku.
public string[] Split (char separator, int count, StringSplitOptions options = System.StringSplitOptions.None);
member this.Split : char * int * StringSplitOptions -> string[]
Public Function Split (separator As Char, count As Integer, Optional options As StringSplitOptions = System.StringSplitOptions.None) As String()
Parametry
- separator
- Char
Znak, který odděluje podřetětce v této instanci.
- count
- Int32
Maximální počet prvků očekávaných v matici
- options
- StringSplitOptions
Bitové kombinace hodnot výčtu, která určuje, zda se mají oříznout podřetězce a zahrnout prázdné podřetězcece.
Návraty
Pole obsahující nejvíce count
podřetětěce z této instance, které jsou oddělené znakem separator
.
Poznámky
Pokud byl řetězec již rozdělen count
– 1krát, ale konec řetězce nebyl dosažen, bude poslední řetězec ve vrácené matici obsahovat zbývající koncový podřetězc této instance beze změny.
Platí pro
Split(Char[], Int32, StringSplitOptions)
- Zdroj:
- String.Manipulation.cs
- Zdroj:
- String.Manipulation.cs
- Zdroj:
- String.Manipulation.cs
Rozdělí řetězec na maximální počet podřetězc na základě zadaných oddělovacích znaků a volitelně i možností.
public:
cli::array <System::String ^> ^ Split(cli::array <char> ^ separator, int count, StringSplitOptions options);
public string[] Split (char[] separator, int count, StringSplitOptions options);
public string[] Split (char[]? separator, int count, StringSplitOptions options);
[System.Runtime.InteropServices.ComVisible(false)]
public string[] Split (char[] separator, int count, StringSplitOptions options);
member this.Split : char[] * int * StringSplitOptions -> string[]
[<System.Runtime.InteropServices.ComVisible(false)>]
member this.Split : char[] * int * StringSplitOptions -> string[]
Public Function Split (separator As Char(), count As Integer, options As StringSplitOptions) As String()
Parametry
- separator
- Char[]
Pole znaků, které odličují podřetězce v tomto řetězci, prázdné pole, které neobsahuje žádné oddělovače, nebo null
.
- count
- Int32
Maximální počet podřetěžků, které se mají vrátit.
- options
- StringSplitOptions
Bitové kombinace hodnot výčtu, která určuje, zda se mají oříznout podřetězce a zahrnout prázdné podřetězcece.
Návraty
Pole obsahující podřetězce v tomto řetězci, které jsou oddělené jedním nebo více znaky v separator
souboru . Další informace najdete v části Poznámky.
- Atributy
Výjimky
count
je negativní.
options
není jednou z StringSplitOptions hodnot.
Příklady
Následující příklad používá StringSplitOptions výčet k zahrnutí nebo vyloučení podřetězu vygenerovaných metodou Split .
// This example demonstrates the String.Split(Char[], Boolean) and
// String.Split(Char[], Int32, Boolean) methods
using namespace System;
void Show( array<String^>^entries )
{
Console::WriteLine( "The return value contains these {0} elements:", entries->Length );
System::Collections::IEnumerator^ myEnum = entries->GetEnumerator();
while ( myEnum->MoveNext() )
{
String^ entry = safe_cast<String^>(myEnum->Current);
Console::Write( "<{0}>", entry );
}
Console::Write( "{0}{0}", Environment::NewLine );
}
int main()
{
String^ s = ",one,,,two,,,,,three,,";
array<Char>^sep = gcnew array<Char>{
','
};
array<String^>^result;
//
Console::WriteLine( "The original string is \"{0}\".", s );
Console::WriteLine( "The separation character is '{0}'.", sep[ 0 ] );
Console::WriteLine();
//
Console::WriteLine( "Split the string and return all elements:" );
result = s->Split( sep, StringSplitOptions::None );
Show( result );
//
Console::WriteLine( "Split the string and return all non-empty elements:" );
result = s->Split( sep, StringSplitOptions::RemoveEmptyEntries );
Show( result );
//
Console::WriteLine( "Split the string and return 2 elements:" );
result = s->Split( sep, 2, StringSplitOptions::None );
Show( result );
//
Console::WriteLine( "Split the string and return 2 non-empty elements:" );
result = s->Split( sep, 2, StringSplitOptions::RemoveEmptyEntries );
Show( result );
}
/*
This example produces the following results:
The original string is ",one,,,two,,,,,three,,".
The separation character is ','.
Split the string and return all elements:
The return value contains these 12 elements:
<><one><><><two><><><><><three><><>
Split the string and return all non-empty elements:
The return value contains these 3 elements:
<one><two><three>
Split the string and return 2 elements:
The return value contains these 2 elements:
<><one,,,two,,,,,three,,>
Split the string and return 2 non-empty elements:
The return value contains these 2 elements:
<one><,,two,,,,,three,,>
*/
// This example demonstrates the String.Split() methods that use
// the StringSplitOptions enumeration.
string s1 = ",ONE,,TWO,,,THREE,,";
string s2 = "[stop]" +
"ONE[stop][stop]" +
"TWO[stop][stop][stop]" +
"THREE[stop][stop]";
char[] charSeparators = new char[] { ',' };
string[] stringSeparators = new string[] { "[stop]" };
string[] result;
// ------------------------------------------------------------------------------
// Split a string delimited by characters.
// ------------------------------------------------------------------------------
Console.WriteLine("1) Split a string delimited by characters:\n");
// Display the original string and delimiter characters.
Console.WriteLine($"1a) The original string is \"{s1}\".");
Console.WriteLine($"The delimiter character is '{charSeparators[0]}'.\n");
// Split a string delimited by characters and return all elements.
Console.WriteLine("1b) Split a string delimited by characters and " +
"return all elements:");
result = s1.Split(charSeparators, StringSplitOptions.None);
Show(result);
// Split a string delimited by characters and return all non-empty elements.
Console.WriteLine("1c) Split a string delimited by characters and " +
"return all non-empty elements:");
result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// Split the original string into the string and empty string before the
// delimiter and the remainder of the original string after the delimiter.
Console.WriteLine("1d) Split a string delimited by characters and " +
"return 2 elements:");
result = s1.Split(charSeparators, 2, StringSplitOptions.None);
Show(result);
// Split the original string into the string after the delimiter and the
// remainder of the original string after the delimiter.
Console.WriteLine("1e) Split a string delimited by characters and " +
"return 2 non-empty elements:");
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// ------------------------------------------------------------------------------
// Split a string delimited by another string.
// ------------------------------------------------------------------------------
Console.WriteLine("2) Split a string delimited by another string:\n");
// Display the original string and delimiter string.
Console.WriteLine($"2a) The original string is \"{s2}\".");
Console.WriteLine($"The delimiter string is \"{stringSeparators[0]}\".\n");
// Split a string delimited by another string and return all elements.
Console.WriteLine("2b) Split a string delimited by another string and " +
"return all elements:");
result = s2.Split(stringSeparators, StringSplitOptions.None);
Show(result);
// Split the original string at the delimiter and return all non-empty elements.
Console.WriteLine("2c) Split a string delimited by another string and " +
"return all non-empty elements:");
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// Split the original string into the empty string before the
// delimiter and the remainder of the original string after the delimiter.
Console.WriteLine("2d) Split a string delimited by another string and " +
"return 2 elements:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.None);
Show(result);
// Split the original string into the string after the delimiter and the
// remainder of the original string after the delimiter.
Console.WriteLine("2e) Split a string delimited by another string and " +
"return 2 non-empty elements:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// Display the array of separated strings using a local function
void Show(string[] entries)
{
Console.WriteLine($"The return value contains these {entries.Length} elements:");
foreach (string entry in entries)
{
Console.Write($"<{entry}>");
}
Console.Write("\n\n");
}
/*
This example produces the following results:
1) Split a string delimited by characters:
1a) The original string is ",ONE,,TWO,,,THREE,,".
The delimiter character is ','.
1b) Split a string delimited by characters and return all elements:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>
1c) Split a string delimited by characters and return all non-empty elements:
The return value contains these 3 elements:
<ONE><TWO><THREE>
1d) Split a string delimited by characters and return 2 elements:
The return value contains these 2 elements:
<><ONE,,TWO,,,THREE,,>
1e) Split a string delimited by characters and return 2 non-empty elements:
The return value contains these 2 elements:
<ONE><TWO,,,THREE,,>
2) Split a string delimited by another string:
2a) The original string is "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".
The delimiter string is "[stop]".
2b) Split a string delimited by another string and return all elements:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>
2c) Split a string delimited by another string and return all non-empty elements:
The return value contains these 3 elements:
<ONE><TWO><THREE>
2d) Split a string delimited by another string and return 2 elements:
The return value contains these 2 elements:
<><ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]>
2e) Split a string delimited by another string and return 2 non-empty elements:
The return value contains these 2 elements:
<ONE><TWO[stop][stop][stop]THREE[stop][stop]>
*/
// 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"
let s1 = ",ONE,,TWO,,,THREE,,"
let s2 = "[stop]" +
"ONE[stop][stop]" +
"TWO[stop][stop][stop]" +
"THREE[stop][stop]"
let charSeparators = [| ',' |]
let stringSeparators = [| "[stop]" |]
// ------------------------------------------------------------------------------
// Split a string delimited by characters.
// ------------------------------------------------------------------------------
printfn "1) Split a string delimited by characters:\n"
// Display the original string and delimiter characters.
printfn $"1a) The original string is \"{s1}\"."
printfn $"The delimiter character is '{charSeparators[0]}'.\n"
// Split a string delimited by characters and return all elements.
printfn "1b) Split a string delimited by characters and return all elements:"
let result = s1.Split(charSeparators, StringSplitOptions.None)
show result
// Split a string delimited by characters and return all non-empty elements.
printfn "1c) Split a string delimited by characters and return all non-empty elements:"
let result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries)
show result
// Split the original string into the string and empty string before the
// delimiter and the remainder of the original string after the delimiter.
printfn "1d) Split a string delimited by characters and return 2 elements:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.None)
show result
// Split the original string into the string after the delimiter and the
// remainder of the original string after the delimiter.
printfn "1e) Split a string delimited by characters and return 2 non-empty elements:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
show result
// ------------------------------------------------------------------------------
// Split a string delimited by another string.
// ------------------------------------------------------------------------------
printfn "2) Split a string delimited by another string:\n"
// Display the original string and delimiter string.
printfn $"2a) The original string is \"{s2}\"."
printfn $"The delimiter string is \"{stringSeparators[0]}\".\n"
// Split a string delimited by another string and return all elements.
printfn "2b) Split a string delimited by another string and return all elements:"
let result = s2.Split(stringSeparators, StringSplitOptions.None)
show result
// Split the original string at the delimiter and return all non-empty elements.
printfn "2c) Split a string delimited by another string and return all non-empty elements:"
let result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)
show result
// Split the original string into the empty string before the
// delimiter and the remainder of the original string after the delimiter.
printfn "2d) Split a string delimited by another string and return 2 elements:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.None)
show result
// Split the original string into the string after the delimiter and the
// remainder of the original string after the delimiter.
printfn "2e) Split a string delimited by another string and return 2 non-empty elements:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
show result
(*
This example produces the following results:
1) Split a string delimited by characters:
1a) The original string is ",ONE,,TWO,,,THREE,,".
The delimiter character is ','.
1b) Split a string delimited by characters and return all elements:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>
1c) Split a string delimited by characters and return all non-empty elements:
The return value contains these 3 elements:
<ONE><TWO><THREE>
1d) Split a string delimited by characters and return 2 elements:
The return value contains these 2 elements:
<><ONE,,TWO,,,THREE,,>
1e) Split a string delimited by characters and return 2 non-empty elements:
The return value contains these 2 elements:
<ONE><TWO,,,THREE,,>
2) Split a string delimited by another string:
2a) The original string is "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".
The delimiter string is "[stop]".
2b) Split a string delimited by another string and return all elements:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>
2c) Split a string delimited by another string and return all non-empty elements:
The return value contains these 3 elements:
<ONE><TWO><THREE>
2d) Split a string delimited by another string and return 2 elements:
The return value contains these 2 elements:
<><ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]>
2e) Split a string delimited by another string and return 2 non-empty elements:
The return value contains these 2 elements:
<ONE><TWO[stop][stop][stop]THREE[stop][stop]>
*)
Dim s1 As String = ",ONE,,TWO,,,THREE,,"
Dim s2 As String = "[stop]" &
"ONE[stop][stop]" &
"TWO[stop][stop][stop]" &
"THREE[stop][stop]"
Dim charSeparators() As Char = {","c}
Dim stringSeparators() As String = {"[stop]"}
Dim result() As String
' ------------------------------------------------------------------------------
' Split a string delimited by characters.
' ------------------------------------------------------------------------------
Console.WriteLine("1) Split a string delimited by characters:" & vbCrLf)
' Display the original string and delimiter characters.
Console.WriteLine("1a) The original string is ""{0}"".", s1)
Console.WriteLine("The delimiter character is '{0}'." & vbCrLf, charSeparators(0))
' Split a string delimited by characters and return all elements.
Console.WriteLine("1b) Split a string delimited by characters and " &
"return all elements:")
result = s1.Split(charSeparators, StringSplitOptions.None)
Show(result)
' Split a string delimited by characters and return all non-empty elements.
Console.WriteLine("1c) Split a string delimited by characters and " &
"return all non-empty elements:")
result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries)
Show(result)
' Split the original string into the string and empty string before the
' delimiter and the remainder of the original string after the delimiter.
Console.WriteLine("1d) Split a string delimited by characters and " &
"return 2 elements:")
result = s1.Split(charSeparators, 2, StringSplitOptions.None)
Show(result)
' Split the original string into the string after the delimiter and the
' remainder of the original string after the delimiter.
Console.WriteLine("1e) Split a string delimited by characters and " &
"return 2 non-empty elements:")
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
Show(result)
' ------------------------------------------------------------------------------
' Split a string delimited by another string.
' ------------------------------------------------------------------------------
Console.WriteLine("2) Split a string delimited by another string:" & vbCrLf)
' Display the original string and delimiter string.
Console.WriteLine("2a) The original string is ""{0}"".", s2)
Console.WriteLine("The delimiter string is ""{0}""." & vbCrLf, stringSeparators(0))
' Split a string delimited by another string and return all elements.
Console.WriteLine("2b) Split a string delimited by another string and " &
"return all elements:")
result = s2.Split(stringSeparators, StringSplitOptions.None)
Show(result)
' Split the original string at the delimiter and return all non-empty elements.
Console.WriteLine("2c) Split a string delimited by another string and " &
"return all non-empty elements:")
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)
Show(result)
' Split the original string into the empty string before the
' delimiter and the remainder of the original string after the delimiter.
Console.WriteLine("2d) Split a string delimited by another string and " &
"return 2 elements:")
result = s2.Split(stringSeparators, 2, StringSplitOptions.None)
Show(result)
' Split the original string into the string after the delimiter and the
' remainder of the original string after the delimiter.
Console.WriteLine("2e) Split a string delimited by another string and " &
"return 2 non-empty elements:")
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
Show(result)
End Sub
' Display the array of separated strings.
Public Shared Sub Show(ByVal entries() As String)
Console.WriteLine("The return value contains these {0} elements:", entries.Length)
Dim entry As String
For Each entry In entries
Console.Write("<{0}>", entry)
Next entry
Console.Write(vbCrLf & vbCrLf)
End Sub
'This example produces the following results:
'
'1) Split a string delimited by characters:
'
'1a) The original string is ",ONE,,TWO,,,THREE,,".
'The delimiter character is ','.
'
'1b) Split a string delimited by characters and return all elements:
'The return value contains these 9 elements:
'<><ONE><><TWO><><><THREE><><>
'
'1c) Split a string delimited by characters and return all non-empty elements:
'The return value contains these 3 elements:
'<ONE><TWO><THREE>
'
'1d) Split a string delimited by characters and return 2 elements:
'The return value contains these 2 elements:
'<><ONE,,TWO,,,THREE,,>
'
'1e) Split a string delimited by characters and return 2 non-empty elements:
'The return value contains these 2 elements:
'<ONE><TWO,,,THREE,,>
'
'2) Split a string delimited by another string:
'
'2a) The original string is "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".
'The delimiter string is "[stop]".
'
'2b) Split a string delimited by another string and return all elements:
'The return value contains these 9 elements:
'<><ONE><><TWO><><><THREE><><>
'
'2c) Split a string delimited by another string and return all non-empty elements:
'The return value contains these 3 elements:
'<ONE><TWO><THREE>
'
'2d) Split a string delimited by another string and return 2 elements:
'The return value contains these 2 elements:
'<><ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]>
'
'2e) Split a string delimited by another string and return 2 non-empty elements:
'The return value contains these 2 elements:
'<ONE><TWO[stop][stop][stop]THREE[stop][stop]>
'
Poznámky
Znaky oddělovače nejsou zahrnuty v prvcích vráceného pole.
Pokud tato instance neobsahuje žádné znaky v separator
nebo count
parametr je 1, vrácené pole se skládá z jednoho prvku, který obsahuje tuto instanci.
separator
Pokud parametr je null
nebo neobsahuje žádné znaky, předpokládá se, že oddělovačem jsou prázdné znaky. Prázdné znaky jsou definovány standardem Unicode a Char.IsWhiteSpace metoda vrátí true
, pokud jsou do ní předány.
null
char[] separator
Pokud chcete předat parametr, musíte označit typ parametrunull
, který má určit nejednoznačnost volání z některých jiných přetížení, například Split(String[], Int32, StringSplitOptions). Následující příklad ukazuje několik způsobů k jednoznačné identifikaci tohoto přetížení.
string phrase = "The quick brown fox";
_ = phrase.Split(default(char[]), 3, StringSplitOptions.RemoveEmptyEntries);
_ = phrase.Split((char[]?)null, 3, StringSplitOptions.RemoveEmptyEntries);
_ = phrase.Split(null as char[], 3, StringSplitOptions.RemoveEmptyEntries);
let phrase = "The quick brown fox"
phrase.Split(Unchecked.defaultof<char[]>, 3, StringSplitOptions.RemoveEmptyEntries) |> ignore
phrase.Split(null :> char[], 3, StringSplitOptions.RemoveEmptyEntries) |> ignore
phrase.Split((null: char[]), 3, StringSplitOptions.RemoveEmptyEntries) |> ignore
Dim phrase As String = "The quick brown fox"
Dim words() As String
words = phrase.Split(TryCast(Nothing, Char()), 3,
StringSplitOptions.RemoveEmptyEntries)
words = phrase.Split(New Char() {}, 3,
StringSplitOptions.RemoveEmptyEntries)
count
Pokud je parametr nula nebo options
je parametr RemoveEmptyEntries a délka této instance je nula, vrátí se prázdné pole.
Každý prvek definuje separator
samostatný znak oddělovače. options
Pokud je Noneparametr , a dva oddělovače jsou sousedící nebo oddělovač je nalezen na začátku nebo na konci této instance, odpovídající prvek matice obsahuje Empty.
Pokud v této instanci existuje více než count
podřetětěce, první count
minus 1 podřetěžcece jsou vráceny v prvním count
minus 1 prvky návratové hodnoty a zbývající znaky v této instanci jsou vráceny v posledním prvku návratové hodnoty.
Pokud count
je větší než počet podřetězen, vrátí se dostupné podřetětěcece a nevyvolá se žádná výjimka.
Otázky výkonu
Metody Split přidělují paměť pro vrácený objekt pole a String objekt pro každý prvek pole. Pokud vaše aplikace vyžaduje optimální výkon nebo pokud je správa přidělení paměti ve vaší aplikaci kritická, zvažte použití IndexOf metody nebo IndexOfAny a volitelně metody k vyhledání podřetězce Compare v řetězci.
Pokud rozdělujete řetězec na znak oddělovače, použijte metodu IndexOf nebo IndexOfAny k vyhledání znaku oddělovače v řetězci. Pokud rozdělujete řetězec na řetězec oddělovače, použijte metodu IndexOf nebo IndexOfAny k vyhledání prvního znaku oddělovače řetězce. Pak pomocí Compare metody určete, zda se znaky za tímto prvním znakem rovnají zbývajícím znakům řetězce oddělovače.
Pokud se navíc stejná sada znaků používá k rozdělení řetězců ve více Split voláních metod, zvažte vytvoření jednoho pole a odkazování na ni v každém volání metody. To významně snižuje režii dalšího volání metody.
Poznámky pro volající
V rozhraní .NET Framework 3.5 a starších verzích, pokud Split(Char[]) je metoda předána separator
null
nebo neobsahuje žádné znaky, metoda používá mírně odlišnou sadu prázdných znaků rozdělit řetězec než Trim(Char[]) metoda oříznout řetězec. Počínaje rozhraním .NET Framework 4 používají obě metody identickou sadu prázdných znaků unicode.
Platí pro
Split(String, Int32, StringSplitOptions)
- Zdroj:
- String.Manipulation.cs
- Zdroj:
- String.Manipulation.cs
- Zdroj:
- String.Manipulation.cs
Rozdělí řetězec na maximální počet podřetězc na základě zadaného řetězce oddělovače a volitelně i možností.
public string[] Split (string? separator, int count, StringSplitOptions options = System.StringSplitOptions.None);
public string[] Split (string separator, int count, StringSplitOptions options = System.StringSplitOptions.None);
member this.Split : string * int * StringSplitOptions -> string[]
Public Function Split (separator As String, count As Integer, Optional options As StringSplitOptions = System.StringSplitOptions.None) As String()
Parametry
- separator
- String
Řetězec, který odděluje podřetězce v této instanci.
- count
- Int32
Maximální počet prvků očekávaných v matici
- options
- StringSplitOptions
Bitové kombinace hodnot výčtu, která určuje, zda se mají oříznout podřetězce a zahrnout prázdné podřetězcece.
Návraty
Pole obsahující nejvíce count
podřetětěce z této instance, které jsou oddělené znakem separator
.
Poznámky
Pokud byl řetězec již rozdělen count
– 1krát, ale konec řetězce nebyl dosažen, bude poslední řetězec ve vrácené matici obsahovat zbývající koncový podřetězc této instance beze změny.
Platí pro
Split(String[], Int32, StringSplitOptions)
- Zdroj:
- String.Manipulation.cs
- Zdroj:
- String.Manipulation.cs
- Zdroj:
- String.Manipulation.cs
Rozdělí řetězec na maximální počet podřetězc na základě zadaných oddělovacích řetězců a volitelně i možností.
public:
cli::array <System::String ^> ^ Split(cli::array <System::String ^> ^ separator, int count, StringSplitOptions options);
public string[] Split (string[] separator, int count, StringSplitOptions options);
public string[] Split (string[]? separator, int count, StringSplitOptions options);
[System.Runtime.InteropServices.ComVisible(false)]
public string[] Split (string[] separator, int count, StringSplitOptions options);
member this.Split : string[] * int * StringSplitOptions -> string[]
[<System.Runtime.InteropServices.ComVisible(false)>]
member this.Split : string[] * int * StringSplitOptions -> string[]
Public Function Split (separator As String(), count As Integer, options As StringSplitOptions) As String()
Parametry
- separator
- String[]
Řetězce, které odlišují podřetězce v tomto řetězci, prázdné pole, které neobsahuje žádné oddělovače, nebo null
.
- count
- Int32
Maximální počet podřetěžků, které se mají vrátit.
- options
- StringSplitOptions
Bitové kombinace hodnot výčtu, která určuje, zda se mají oříznout podřetězce a zahrnout prázdné podřetězcece.
Návraty
Pole, jehož prvky obsahují podřetězce v tomto řetězci, které jsou oddělené jedním nebo více řetězci v separator
. Další informace najdete v části Poznámky.
- Atributy
Výjimky
count
je negativní.
options
není jednou z StringSplitOptions hodnot.
Příklady
Následující příklad používá StringSplitOptions výčet k zahrnutí nebo vyloučení podřetězu vygenerovaných metodou Split .
// This example demonstrates the String.Split(Char[], Boolean) and
// String.Split(Char[], Int32, Boolean) methods
using namespace System;
void Show( array<String^>^entries )
{
Console::WriteLine( "The return value contains these {0} elements:", entries->Length );
System::Collections::IEnumerator^ myEnum = entries->GetEnumerator();
while ( myEnum->MoveNext() )
{
String^ entry = safe_cast<String^>(myEnum->Current);
Console::Write( "<{0}>", entry );
}
Console::Write( "{0}{0}", Environment::NewLine );
}
int main()
{
String^ s = ",one,,,two,,,,,three,,";
array<Char>^sep = gcnew array<Char>{
','
};
array<String^>^result;
//
Console::WriteLine( "The original string is \"{0}\".", s );
Console::WriteLine( "The separation character is '{0}'.", sep[ 0 ] );
Console::WriteLine();
//
Console::WriteLine( "Split the string and return all elements:" );
result = s->Split( sep, StringSplitOptions::None );
Show( result );
//
Console::WriteLine( "Split the string and return all non-empty elements:" );
result = s->Split( sep, StringSplitOptions::RemoveEmptyEntries );
Show( result );
//
Console::WriteLine( "Split the string and return 2 elements:" );
result = s->Split( sep, 2, StringSplitOptions::None );
Show( result );
//
Console::WriteLine( "Split the string and return 2 non-empty elements:" );
result = s->Split( sep, 2, StringSplitOptions::RemoveEmptyEntries );
Show( result );
}
/*
This example produces the following results:
The original string is ",one,,,two,,,,,three,,".
The separation character is ','.
Split the string and return all elements:
The return value contains these 12 elements:
<><one><><><two><><><><><three><><>
Split the string and return all non-empty elements:
The return value contains these 3 elements:
<one><two><three>
Split the string and return 2 elements:
The return value contains these 2 elements:
<><one,,,two,,,,,three,,>
Split the string and return 2 non-empty elements:
The return value contains these 2 elements:
<one><,,two,,,,,three,,>
*/
// This example demonstrates the String.Split() methods that use
// the StringSplitOptions enumeration.
string s1 = ",ONE,,TWO,,,THREE,,";
string s2 = "[stop]" +
"ONE[stop][stop]" +
"TWO[stop][stop][stop]" +
"THREE[stop][stop]";
char[] charSeparators = new char[] { ',' };
string[] stringSeparators = new string[] { "[stop]" };
string[] result;
// ------------------------------------------------------------------------------
// Split a string delimited by characters.
// ------------------------------------------------------------------------------
Console.WriteLine("1) Split a string delimited by characters:\n");
// Display the original string and delimiter characters.
Console.WriteLine($"1a) The original string is \"{s1}\".");
Console.WriteLine($"The delimiter character is '{charSeparators[0]}'.\n");
// Split a string delimited by characters and return all elements.
Console.WriteLine("1b) Split a string delimited by characters and " +
"return all elements:");
result = s1.Split(charSeparators, StringSplitOptions.None);
Show(result);
// Split a string delimited by characters and return all non-empty elements.
Console.WriteLine("1c) Split a string delimited by characters and " +
"return all non-empty elements:");
result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// Split the original string into the string and empty string before the
// delimiter and the remainder of the original string after the delimiter.
Console.WriteLine("1d) Split a string delimited by characters and " +
"return 2 elements:");
result = s1.Split(charSeparators, 2, StringSplitOptions.None);
Show(result);
// Split the original string into the string after the delimiter and the
// remainder of the original string after the delimiter.
Console.WriteLine("1e) Split a string delimited by characters and " +
"return 2 non-empty elements:");
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// ------------------------------------------------------------------------------
// Split a string delimited by another string.
// ------------------------------------------------------------------------------
Console.WriteLine("2) Split a string delimited by another string:\n");
// Display the original string and delimiter string.
Console.WriteLine($"2a) The original string is \"{s2}\".");
Console.WriteLine($"The delimiter string is \"{stringSeparators[0]}\".\n");
// Split a string delimited by another string and return all elements.
Console.WriteLine("2b) Split a string delimited by another string and " +
"return all elements:");
result = s2.Split(stringSeparators, StringSplitOptions.None);
Show(result);
// Split the original string at the delimiter and return all non-empty elements.
Console.WriteLine("2c) Split a string delimited by another string and " +
"return all non-empty elements:");
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// Split the original string into the empty string before the
// delimiter and the remainder of the original string after the delimiter.
Console.WriteLine("2d) Split a string delimited by another string and " +
"return 2 elements:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.None);
Show(result);
// Split the original string into the string after the delimiter and the
// remainder of the original string after the delimiter.
Console.WriteLine("2e) Split a string delimited by another string and " +
"return 2 non-empty elements:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// Display the array of separated strings using a local function
void Show(string[] entries)
{
Console.WriteLine($"The return value contains these {entries.Length} elements:");
foreach (string entry in entries)
{
Console.Write($"<{entry}>");
}
Console.Write("\n\n");
}
/*
This example produces the following results:
1) Split a string delimited by characters:
1a) The original string is ",ONE,,TWO,,,THREE,,".
The delimiter character is ','.
1b) Split a string delimited by characters and return all elements:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>
1c) Split a string delimited by characters and return all non-empty elements:
The return value contains these 3 elements:
<ONE><TWO><THREE>
1d) Split a string delimited by characters and return 2 elements:
The return value contains these 2 elements:
<><ONE,,TWO,,,THREE,,>
1e) Split a string delimited by characters and return 2 non-empty elements:
The return value contains these 2 elements:
<ONE><TWO,,,THREE,,>
2) Split a string delimited by another string:
2a) The original string is "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".
The delimiter string is "[stop]".
2b) Split a string delimited by another string and return all elements:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>
2c) Split a string delimited by another string and return all non-empty elements:
The return value contains these 3 elements:
<ONE><TWO><THREE>
2d) Split a string delimited by another string and return 2 elements:
The return value contains these 2 elements:
<><ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]>
2e) Split a string delimited by another string and return 2 non-empty elements:
The return value contains these 2 elements:
<ONE><TWO[stop][stop][stop]THREE[stop][stop]>
*/
// 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"
let s1 = ",ONE,,TWO,,,THREE,,"
let s2 = "[stop]" +
"ONE[stop][stop]" +
"TWO[stop][stop][stop]" +
"THREE[stop][stop]"
let charSeparators = [| ',' |]
let stringSeparators = [| "[stop]" |]
// ------------------------------------------------------------------------------
// Split a string delimited by characters.
// ------------------------------------------------------------------------------
printfn "1) Split a string delimited by characters:\n"
// Display the original string and delimiter characters.
printfn $"1a) The original string is \"{s1}\"."
printfn $"The delimiter character is '{charSeparators[0]}'.\n"
// Split a string delimited by characters and return all elements.
printfn "1b) Split a string delimited by characters and return all elements:"
let result = s1.Split(charSeparators, StringSplitOptions.None)
show result
// Split a string delimited by characters and return all non-empty elements.
printfn "1c) Split a string delimited by characters and return all non-empty elements:"
let result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries)
show result
// Split the original string into the string and empty string before the
// delimiter and the remainder of the original string after the delimiter.
printfn "1d) Split a string delimited by characters and return 2 elements:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.None)
show result
// Split the original string into the string after the delimiter and the
// remainder of the original string after the delimiter.
printfn "1e) Split a string delimited by characters and return 2 non-empty elements:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
show result
// ------------------------------------------------------------------------------
// Split a string delimited by another string.
// ------------------------------------------------------------------------------
printfn "2) Split a string delimited by another string:\n"
// Display the original string and delimiter string.
printfn $"2a) The original string is \"{s2}\"."
printfn $"The delimiter string is \"{stringSeparators[0]}\".\n"
// Split a string delimited by another string and return all elements.
printfn "2b) Split a string delimited by another string and return all elements:"
let result = s2.Split(stringSeparators, StringSplitOptions.None)
show result
// Split the original string at the delimiter and return all non-empty elements.
printfn "2c) Split a string delimited by another string and return all non-empty elements:"
let result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)
show result
// Split the original string into the empty string before the
// delimiter and the remainder of the original string after the delimiter.
printfn "2d) Split a string delimited by another string and return 2 elements:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.None)
show result
// Split the original string into the string after the delimiter and the
// remainder of the original string after the delimiter.
printfn "2e) Split a string delimited by another string and return 2 non-empty elements:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
show result
(*
This example produces the following results:
1) Split a string delimited by characters:
1a) The original string is ",ONE,,TWO,,,THREE,,".
The delimiter character is ','.
1b) Split a string delimited by characters and return all elements:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>
1c) Split a string delimited by characters and return all non-empty elements:
The return value contains these 3 elements:
<ONE><TWO><THREE>
1d) Split a string delimited by characters and return 2 elements:
The return value contains these 2 elements:
<><ONE,,TWO,,,THREE,,>
1e) Split a string delimited by characters and return 2 non-empty elements:
The return value contains these 2 elements:
<ONE><TWO,,,THREE,,>
2) Split a string delimited by another string:
2a) The original string is "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".
The delimiter string is "[stop]".
2b) Split a string delimited by another string and return all elements:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>
2c) Split a string delimited by another string and return all non-empty elements:
The return value contains these 3 elements:
<ONE><TWO><THREE>
2d) Split a string delimited by another string and return 2 elements:
The return value contains these 2 elements:
<><ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]>
2e) Split a string delimited by another string and return 2 non-empty elements:
The return value contains these 2 elements:
<ONE><TWO[stop][stop][stop]THREE[stop][stop]>
*)
Dim s1 As String = ",ONE,,TWO,,,THREE,,"
Dim s2 As String = "[stop]" &
"ONE[stop][stop]" &
"TWO[stop][stop][stop]" &
"THREE[stop][stop]"
Dim charSeparators() As Char = {","c}
Dim stringSeparators() As String = {"[stop]"}
Dim result() As String
' ------------------------------------------------------------------------------
' Split a string delimited by characters.
' ------------------------------------------------------------------------------
Console.WriteLine("1) Split a string delimited by characters:" & vbCrLf)
' Display the original string and delimiter characters.
Console.WriteLine("1a) The original string is ""{0}"".", s1)
Console.WriteLine("The delimiter character is '{0}'." & vbCrLf, charSeparators(0))
' Split a string delimited by characters and return all elements.
Console.WriteLine("1b) Split a string delimited by characters and " &
"return all elements:")
result = s1.Split(charSeparators, StringSplitOptions.None)
Show(result)
' Split a string delimited by characters and return all non-empty elements.
Console.WriteLine("1c) Split a string delimited by characters and " &
"return all non-empty elements:")
result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries)
Show(result)
' Split the original string into the string and empty string before the
' delimiter and the remainder of the original string after the delimiter.
Console.WriteLine("1d) Split a string delimited by characters and " &
"return 2 elements:")
result = s1.Split(charSeparators, 2, StringSplitOptions.None)
Show(result)
' Split the original string into the string after the delimiter and the
' remainder of the original string after the delimiter.
Console.WriteLine("1e) Split a string delimited by characters and " &
"return 2 non-empty elements:")
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
Show(result)
' ------------------------------------------------------------------------------
' Split a string delimited by another string.
' ------------------------------------------------------------------------------
Console.WriteLine("2) Split a string delimited by another string:" & vbCrLf)
' Display the original string and delimiter string.
Console.WriteLine("2a) The original string is ""{0}"".", s2)
Console.WriteLine("The delimiter string is ""{0}""." & vbCrLf, stringSeparators(0))
' Split a string delimited by another string and return all elements.
Console.WriteLine("2b) Split a string delimited by another string and " &
"return all elements:")
result = s2.Split(stringSeparators, StringSplitOptions.None)
Show(result)
' Split the original string at the delimiter and return all non-empty elements.
Console.WriteLine("2c) Split a string delimited by another string and " &
"return all non-empty elements:")
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)
Show(result)
' Split the original string into the empty string before the
' delimiter and the remainder of the original string after the delimiter.
Console.WriteLine("2d) Split a string delimited by another string and " &
"return 2 elements:")
result = s2.Split(stringSeparators, 2, StringSplitOptions.None)
Show(result)
' Split the original string into the string after the delimiter and the
' remainder of the original string after the delimiter.
Console.WriteLine("2e) Split a string delimited by another string and " &
"return 2 non-empty elements:")
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
Show(result)
End Sub
' Display the array of separated strings.
Public Shared Sub Show(ByVal entries() As String)
Console.WriteLine("The return value contains these {0} elements:", entries.Length)
Dim entry As String
For Each entry In entries
Console.Write("<{0}>", entry)
Next entry
Console.Write(vbCrLf & vbCrLf)
End Sub
'This example produces the following results:
'
'1) Split a string delimited by characters:
'
'1a) The original string is ",ONE,,TWO,,,THREE,,".
'The delimiter character is ','.
'
'1b) Split a string delimited by characters and return all elements:
'The return value contains these 9 elements:
'<><ONE><><TWO><><><THREE><><>
'
'1c) Split a string delimited by characters and return all non-empty elements:
'The return value contains these 3 elements:
'<ONE><TWO><THREE>
'
'1d) Split a string delimited by characters and return 2 elements:
'The return value contains these 2 elements:
'<><ONE,,TWO,,,THREE,,>
'
'1e) Split a string delimited by characters and return 2 non-empty elements:
'The return value contains these 2 elements:
'<ONE><TWO,,,THREE,,>
'
'2) Split a string delimited by another string:
'
'2a) The original string is "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".
'The delimiter string is "[stop]".
'
'2b) Split a string delimited by another string and return all elements:
'The return value contains these 9 elements:
'<><ONE><><TWO><><><THREE><><>
'
'2c) Split a string delimited by another string and return all non-empty elements:
'The return value contains these 3 elements:
'<ONE><TWO><THREE>
'
'2d) Split a string delimited by another string and return 2 elements:
'The return value contains these 2 elements:
'<><ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]>
'
'2e) Split a string delimited by another string and return 2 non-empty elements:
'The return value contains these 2 elements:
'<ONE><TWO[stop][stop][stop]THREE[stop][stop]>
'
Poznámky
Řetězce oddělovače nejsou zahrnuty v prvcích vráceného pole.
Pokud tato instance neobsahuje žádný z řetězců v separator
nebo count
parametr je 1, vrácené pole se skládá z jednoho prvku, který obsahuje tuto instanci.
separator
Pokud parametr je null
nebo neobsahuje žádné znaky, předpokládá se, že oddělovačem jsou prázdné znaky. Prázdné znaky jsou definovány standardem Unicode a Char.IsWhiteSpace metoda vrátí true
, pokud jsou do ní předány.
null
string[] separator
Pokud chcete předat parametr, musíte označit typ parametrunull
, který má určit nejednoznačnost volání z některých jiných přetížení, například Split(Char[], Int32, StringSplitOptions). Následující příklad ukazuje několik způsobů k jednoznačné identifikaci tohoto přetížení.
string phrase = "The quick brown fox";
_ = phrase.Split(default(string[]), 3, StringSplitOptions.RemoveEmptyEntries);
_ = phrase.Split((string[]?)null, 3, StringSplitOptions.RemoveEmptyEntries);
_ = phrase.Split(null as string[], 3, StringSplitOptions.RemoveEmptyEntries);
let phrase = "The quick brown fox"
phrase.Split(Unchecked.defaultof<string[]>, 3, StringSplitOptions.RemoveEmptyEntries) |> ignore
phrase.Split(null :> string[], 3, StringSplitOptions.RemoveEmptyEntries) |> ignore
phrase.Split((null: string[]), 3, StringSplitOptions.RemoveEmptyEntries) |> ignore
Dim phrase As String = "The quick brown fox"
Dim words() As String
words = phrase.Split(TryCast(Nothing, String()), 3,
StringSplitOptions.RemoveEmptyEntries)
words = phrase.Split(New String() {}, 3,
StringSplitOptions.RemoveEmptyEntries)
count
Pokud je parametr nula nebo options
je parametr RemoveEmptyEntries a délka této instance je nula, vrátí se prázdné pole.
Každý prvek definuje separator
samostatný oddělovač, který se skládá z jednoho nebo více znaků. options
Pokud je Noneparametr , a dva oddělovače jsou sousedící nebo oddělovač je nalezen na začátku nebo na konci této instance, odpovídající prvek matice obsahuje Empty.
Pokud v této instanci existuje více než count
podřetětěce, první count
minus 1 podřetěžcece jsou vráceny v prvním count
minus 1 prvky návratové hodnoty a zbývající znaky v této instanci jsou vráceny v posledním prvku návratové hodnoty.
Pokud count
je větší než počet podřetězen, vrátí se dostupné podřetětěcece a nevyvolá se žádná výjimka.
Pole oddělovače
Pokud se některý z prvků v separator
souboru skládá z více znaků, považuje se celý podřetězen za oddělovač. Pokud je například jeden z elementů v separator
souboru "10", vrátí pokus o rozdělení řetězce "This10is10a10string". Toto pole se čtyřmi prvky: { "This", "is", "a", "string" }.
Podrobnosti o porovnání
Metoda Split extrahuje podřetězce v tomto řetězci, které jsou oddělené jedním nebo více řetězci v parametru separator
, a vrátí tyto podřetězcece jako prvky pole.
Metoda Split hledá oddělovače provedením porovnání s použitím pravidel řazení řad rozlišujících velká a malá písmena. Další informace o řazení slov, řetězců a řadových řad najdete ve výčtu System.Globalization.CompareOptions .
Metoda Split ignoruje jakýkoli prvek, separator
jehož hodnota je null
nebo prázdný řetězec ("").
Aby se zabránilo nejednoznačným výsledkům, když řetězce v separator
souboru mají společné znaky, Split metoda pokračuje od začátku do konce hodnoty instance a odpovídá prvnímu prvku v separator
instanci, který je roven oddělovači v instanci. Pořadí, ve kterém jsou v instanci nalezeny podřetětěce, má přednost před pořadím prvků v separator
.
Představte si například instanci, jejíž hodnota je "abcdef". Pokud první prvek v souboru separator
byl "ef" a druhý prvek byl "bcde", výsledkem operace rozdělení by byly "a" a "f". Je to proto, že je nalezen podřetěžce v instanci "bcde" a odpovídá elementu v separator
před podřetěžce "f".
Pokud byl první prvek " separator
bcd" a druhý prvek byl "bc", výsledek operace rozdělení by byl "a" a "ef". Je to proto, že "bcd" je první oddělovač, separator
který odpovídá oddělovači v instanci. Pokud bylo pořadí oddělovačů obráceno tak, aby první prvek byl "bc" a druhý prvek byl "bcd", výsledek by byl "a" a "def".
Otázky výkonu
Metody Split přidělují paměť pro vrácený objekt pole a String objekt pro každý prvek pole. Pokud vaše aplikace vyžaduje optimální výkon nebo pokud je správa přidělení paměti ve vaší aplikaci kritická, zvažte použití IndexOf metody nebo IndexOfAny a volitelně metody k vyhledání podřetězce Compare v řetězci.
Pokud rozdělujete řetězec na znak oddělovače, použijte metodu IndexOf nebo IndexOfAny k vyhledání znaku oddělovače v řetězci. Pokud rozdělujete řetězec na řetězec oddělovače, použijte metodu IndexOf nebo IndexOfAny k vyhledání prvního znaku oddělovače řetězce. Pak pomocí Compare metody určete, zda se znaky za tímto prvním znakem rovnají zbývajícím znakům řetězce oddělovače.
Pokud se navíc stejná sada znaků používá k rozdělení řetězců ve více Split voláních metod, zvažte vytvoření jednoho pole a odkazování na ni v každém volání metody. To významně snižuje režii dalšího volání metody.
Poznámky pro volající
V rozhraní .NET Framework 3.5 a starších verzích, pokud Split(Char[]) je metoda předána separator
null
nebo neobsahuje žádné znaky, metoda používá mírně odlišnou sadu prázdných znaků rozdělit řetězec než Trim(Char[]) metoda oříznout řetězec. Počínaje rozhraním .NET Framework 4 používají obě metody identickou sadu prázdných znaků unicode.
Platí pro
Váš názor
https://aka.ms/ContentUserFeedback.
Připravujeme: V průběhu roku 2024 budeme postupně vyřazovat problémy z GitHub coby mechanismus zpětné vazby pro obsah a nahrazovat ho novým systémem zpětné vazby. Další informace naleznete v tématu:Odeslat a zobrazit názory pro