String.Split Yöntem
Tanım
Önemli
Bazı bilgiler ürünün ön sürümüyle ilgilidir ve sürüm öncesinde önemli değişiklikler yapılmış olabilir. Burada verilen bilgilerle ilgili olarak Microsoft açık veya zımni hiçbir garanti vermez.
Bu örnekteki belirli bir dizenin veya Unicode karakter dizisinin öğeleriyle ayrılmış alt dizeleri içeren bir dize dizisi döndürür.
Aşırı Yüklemeler
Split(String, Int32, StringSplitOptions) |
Belirtilen sınırlayıcı dizeye ve isteğe bağlı olarak seçeneklere göre bir dizeyi en fazla sayıda alt dizeye böler. |
Split(Char[], Int32, StringSplitOptions) |
Belirtilen sınırlandırma karakterlerine ve isteğe bağlı olarak seçeneklere göre bir dizeyi en fazla sayıda alt dizeye böler. |
Split(Char, Int32, StringSplitOptions) |
Bir dizeyi belirtilen sınırlayıcı karaktere ve isteğe bağlı olarak seçeneklere göre en fazla sayıda alt dizeye böler. Sağlanan karakter ayırıcısına göre dizeyi en fazla alt dize sayısına böler ve isteğe bağlı olarak sonuçtan boş alt dizeleri atlar. |
Split(String[], StringSplitOptions) |
Belirtilen sınırlayıcı dizeye ve isteğe bağlı olarak seçeneklere göre bir dizeyi alt dizelere böler. |
Split(String, StringSplitOptions) |
Bir dizeyi, sağlanan dize ayırıcısını temel alan alt dizelere böler. |
Split(Char[]) |
Belirtilen sınırlandırma karakterlerine göre bir dizeyi alt dizelere böler. |
Split(Char[], Int32) |
Belirtilen sınırlayıcı karakterlere göre bir dizeyi en fazla alt dize sayısına böler. |
Split(Char, StringSplitOptions) |
Bir dizeyi belirtilen sınırlayıcı karaktere ve isteğe bağlı olarak seçeneklere göre alt dizelere böler. |
Split(ReadOnlySpan<Char>) | |
Split(String[], Int32, StringSplitOptions) |
Belirtilen sınırlayıcı dizelere ve isteğe bağlı olarak seçeneklere göre bir dizeyi en fazla sayıda alt dizeye böler. |
Split(Char[], StringSplitOptions) |
Belirtilen sınırlandırma karakterlerine ve seçeneklerine göre bir dizeyi alt dizelere böler. |
Açıklamalar
Split , sınırlandırılmış bir dizeyi alt dizelere bölmek için kullanılır. Sıfır veya daha fazla sınırlayıcı karakter veya dize belirtmek için karakter dizisi veya dize dizisi kullanabilirsiniz. Sınırlayıcı karakter belirtilmezse, dize boşluk karakterlerine bölünür.
yönteminin Split aşırı yüklemeleri, yöntem tarafından döndürülen alt dize sayısını sınırlamanıza ( Split(Char[], Int32) yöntem), sonuçta boş dizelerin eklenip eklenmeyeceğini ve/veya alt dizelerin kırpılıp kırpılmayacağını ( Split(Char[], StringSplitOptions) ve Split(String[], StringSplitOptions) yöntemleri) belirtmenize veya her ikisini de ( Split(Char[], Int32, StringSplitOptions) ve Split(String[], Int32, StringSplitOptions) yöntemleri) yapmanıza olanak sağlar.
İpucu
Split yöntemi, sınırlandırılmış bir dizeyi alt dizelere bölmenin her zaman en iyi yolu değildir. Sınırlandırılmış bir dizenin tüm alt dizelerini ayıklamak istemiyorsanız veya bir dizeyi sınırlayıcı karakter kümesi yerine bir desene göre ayrıştırmak istiyorsanız, normal ifadeler kullanmayı veya bir karakterin dizinini döndüren arama yöntemlerinden birini yöntemiyle birleştirmeyi Substring göz önünde bulundurun. Daha fazla bilgi için bkz. Dizeden alt dize ayıklama.
Örnek
Aşağıdaki örneklerde üç farklı aşırı yüklemesi String.Split()
gösterilir. İlk örnek aşırı yüklemeyi çağırır Split(Char[]) ve tek bir sınırlayıcıya geçirir.
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.
Gördüğünüz gibi nokta karakterleri (.
) iki alt dizeye dahil edilir. Nokta karakterlerini dışlamak istiyorsanız, nokta karakterini ek bir sınırlandırma karakteri olarak ekleyebilirsiniz. Sonraki örnekte bunun nasıl yapılacağını gösterilmektedir.
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:
Dönemler alt dizelerden silindi, ancak artık fazladan iki boş alt dize dahil edildi. Bu boş alt dize, bir sözcük ile onu izleyen nokta arasındaki alt dizeyi temsil eder. Sonuçta elde edilen dizideki boş alt dizeleri atlayarak aşırı yüklemeyi çağırabilir Split(Char[], StringSplitOptions) ve parametresini options
belirtebilirsinizStringSplitOptions.RemoveEmptyEntries.
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
tek tek aşırı yüklemelerinin String.Split()
bölümleri daha fazla örnek içerir.
Split(String, Int32, StringSplitOptions)
- Kaynak:
- String.Manipulation.cs
- Kaynak:
- String.Manipulation.cs
- Kaynak:
- String.Manipulation.cs
Belirtilen sınırlayıcı dizeye ve isteğe bağlı olarak seçeneklere göre bir dizeyi en fazla sayıda alt dizeye böler.
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()
Parametreler
- separator
- String
Bu örnekteki alt dizeleri sınırlayan bir dize.
- count
- Int32
Dizide beklenen en fazla öğe sayısı.
- options
- StringSplitOptions
Alt dizelerin kırpılıp kırpılmayacağını ve boş alt dizelerin eklenip eklenmeyeceğini belirten numaralandırma değerlerinin bit düzeyinde birleşimi.
Döndürülenler
Bu örnekten en çok count
ile sınırlandırılmış separator
alt dizeler içeren bir dizi.
Açıklamalar
Dize zaten -1 kez bölünmüşse count
, ancak dizenin sonuna ulaşılmamışsa, döndürülen dizideki son dize bu örneğin kalan kalan alt dizesini (dokunulmamış) içerecektir.
Şunlara uygulanır
Split(Char[], Int32, StringSplitOptions)
- Kaynak:
- String.Manipulation.cs
- Kaynak:
- String.Manipulation.cs
- Kaynak:
- String.Manipulation.cs
Belirtilen sınırlandırma karakterlerine ve isteğe bağlı olarak seçeneklere göre bir dizeyi en fazla sayıda alt dizeye böler.
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()
Parametreler
- separator
- Char[]
Bu dizedeki alt dizeleri sınırlandıran bir karakter dizisi, sınırlayıcı içermeyen boş bir dizi veya null
.
- count
- Int32
Döndürülecek en fazla alt dize sayısı.
- options
- StringSplitOptions
Alt dizelerin kırpılıp kırpılmayacağını ve boş alt dizelerin eklenip eklenmeyeceğini belirten numaralandırma değerlerinin bit düzeyinde birleşimi.
Döndürülenler
Bu dizedeki bir veya daha fazla karakterle separator
sınırlandırılmış alt dizeleri içeren bir dizi. Daha fazla bilgi için Açıklamalar bölümüne bakın.
- Öznitelikler
Özel durumlar
count
negatiftir.
options
değerlerden StringSplitOptions biri değildir.
Örnekler
Aşağıdaki örnek, yöntemi tarafından oluşturulan alt dizeleri dahil etmek veya hariç tutmak için numaralandırmayı Split kullanırStringSplitOptions.
// 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.
// Example 1: Split a string delimited by characters
Console.WriteLine("1) Split a string delimited by characters:\n");
string s1 = ",ONE,, TWO,, , THREE,,";
char[] charSeparators = new char[] { ',' };
string[] result;
Console.WriteLine($"The original string is: \"{s1}\".");
Console.WriteLine($"The delimiter character is: '{charSeparators[0]}'.\n");
// Split the string and return all elements
Console.WriteLine("1a) Return all elements:");
result = s1.Split(charSeparators, StringSplitOptions.None);
Show(result);
// Split the string and return all elements with whitespace trimmed
Console.WriteLine("1b) Return all elements with whitespace trimmed:");
result = s1.Split(charSeparators, StringSplitOptions.TrimEntries);
Show(result);
// Split the string and return all non-empty elements
Console.WriteLine("1c) Return all non-empty elements:");
result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// Split the string and return all non-whitespace elements with whitespace trimmed
Console.WriteLine("1d) Return all non-whitespace elements with whitespace trimmed:");
result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
Show(result);
// Split the string into only two elements, keeping the remainder in the last match
Console.WriteLine("1e) Split into only two elements:");
result = s1.Split(charSeparators, 2, StringSplitOptions.None);
Show(result);
// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("1f) Split into only two elements with whitespace trimmed:");
result = s1.Split(charSeparators, 2, StringSplitOptions.TrimEntries);
Show(result);
// Split the string into only two non-empty elements, keeping the remainder in the last match
Console.WriteLine("1g) Split into only two non-empty elements:");
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("1h) Split into only two non-whitespace elements with whitespace trimmed:");
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
Show(result);
// Example 2: Split a string delimited by another string
Console.WriteLine("2) Split a string delimited by another string:\n");
string s2 = "[stop]" +
"ONE[stop] [stop]" +
"TWO [stop][stop] [stop]" +
"THREE[stop][stop] ";
string[] stringSeparators = new string[] { "[stop]" };
Console.WriteLine($"The original string is: \"{s2}\".");
Console.WriteLine($"The delimiter string is: \"{stringSeparators[0]}\".\n");
// Split the string and return all elements
Console.WriteLine("2a) Return all elements:");
result = s2.Split(stringSeparators, StringSplitOptions.None);
Show(result);
// Split the string and return all elements with whitespace trimmed
Console.WriteLine("2b) Return all elements with whitespace trimmed:");
result = s2.Split(stringSeparators, StringSplitOptions.TrimEntries);
Show(result);
// Split the string and return all non-empty elements
Console.WriteLine("2c) Return all non-empty elements:");
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// Split the string and return all non-whitespace elements with whitespace trimmed
Console.WriteLine("2d) Return all non-whitespace elements with whitespace trimmed:");
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
Show(result);
// Split the string into only two elements, keeping the remainder in the last match
Console.WriteLine("2e) Split into only two elements:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.None);
Show(result);
// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("2f) Split into only two elements with whitespace trimmed:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.TrimEntries);
Show(result);
// Split the string into only two non-empty elements, keeping the remainder in the last match
Console.WriteLine("2g) Split into only two non-empty elements:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("2h) Split into only two non-whitespace elements with whitespace trimmed:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
Show(result);
// Display the array of separated strings using a local function
void Show(string[] entries)
{
Console.WriteLine($"The return value contains these {entries.Length} elements:");
foreach (string entry in entries)
{
Console.Write($"<{entry}>");
}
Console.Write("\n\n");
}
/*
This example produces the following results:
1) Split a string delimited by characters:
The original string is: ",ONE,, TWO,, , THREE,,".
The delimiter character is: ','.
1a) Return all elements:
The return value contains these 9 elements:
<><ONE><>< TWO><>< >< THREE><><>
1b) Return all elements with whitespace trimmed:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>
1c) Return all non-empty elements:
The return value contains these 4 elements:
<ONE>< TWO>< >< THREE>
1d) Return all non-whitespace elements with whitespace trimmed:
The return value contains these 3 elements:
<ONE><TWO><THREE>
1e) Split into only two elements:
The return value contains these 2 elements:
<><ONE,, TWO,, , THREE,,>
1f) Split into only two elements with whitespace trimmed:
The return value contains these 2 elements:
<><ONE,, TWO,, , THREE,,>
1g) Split into only two non-empty elements:
The return value contains these 2 elements:
<ONE>< TWO,, , THREE,,>
1h) Split into only two non-whitespace elements with whitespace trimmed:
The return value contains these 2 elements:
<ONE><TWO,, , THREE,,>
2) Split a string delimited by another string:
The original string is: "[stop]ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] ".
The delimiter string is: "[stop]".
2a) Return all elements:
The return value contains these 9 elements:
<><ONE>< ><TWO ><>< ><THREE><>< >
2b) Return all elements with whitespace trimmed:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>
2c) Return all non-empty elements:
The return value contains these 6 elements:
<ONE>< ><TWO >< ><THREE>< >
2d) Return all non-whitespace elements with whitespace trimmed:
The return value contains these 3 elements:
<ONE><TWO><THREE>
2e) Split into only two elements:
The return value contains these 2 elements:
<><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] >
2f) Split into only two elements with whitespace trimmed:
The return value contains these 2 elements:
<><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop]>
2g) Split into only two non-empty elements:
The return value contains these 2 elements:
<ONE>< [stop]TWO [stop][stop] [stop]THREE[stop][stop] >
2h) Split into only two non-whitespace elements with whitespace trimmed:
The return value contains these 2 elements:
<ONE><TWO [stop][stop] [stop]THREE[stop][stop]>
*/
// This example demonstrates the String.Split() methods that use
// the StringSplitOptions enumeration.
// Display the array of separated strings using a local function
let show (entries: string[]) =
printfn $"The return value contains these {entries.Length} elements:"
for entry in entries do
printf $"<{entry}>"
printf "\n\n"
// Example 1: Split a string delimited by characters
printfn "1) Split a string delimited by characters:\n"
let s1 = ",ONE,, TWO,, , THREE,,"
let charSeparators = [| ',' |]
printfn $"The original string is: \"{s1}\"."
printfn $"The delimiter character is: '{charSeparators[0]}'.\n"
// Split the string and return all elements
printfn "1a) Return all elements:"
let result = s1.Split(charSeparators, StringSplitOptions.None)
show result
// Split the string and return all elements with whitespace trimmed
printfn "1b) Return all elements with whitespace trimmed:"
let result = s1.Split(charSeparators, StringSplitOptions.TrimEntries)
show result
// Split the string and return all non-empty elements
printfn "1c) Return all non-empty elements:"
let result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries)
show result
// Split the string and return all non-whitespace elements with whitespace trimmed
printfn "1d) Return all non-whitespace elements with whitespace trimmed:"
let result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)
show result
// Split the string into only two elements, keeping the remainder in the last match
printfn "1e) Split into only two elements:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.None)
show result
// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
printfn "1f) Split into only two elements with whitespace trimmed:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.TrimEntries)
show result
// Split the string into only two non-empty elements, keeping the remainder in the last match
printfn "1g) Split into only two non-empty elements:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
show result
// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
printfn "1h) Split into only two non-whitespace elements with whitespace trimmed:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)
show result
// Example 2: Split a string delimited by another string
printfn "2) Split a string delimited by another string:\n"
let s2 = "[stop]" +
"ONE[stop] [stop]" +
"TWO [stop][stop] [stop]" +
"THREE[stop][stop] "
let stringSeparators = [| "[stop]" |]
printfn $"The original string is: \"{s2}\"."
printfn $"The delimiter string is: \"{stringSeparators[0]}\".\n"
// Split the string and return all elements
printfn "2a) Return all elements:"
let result = s2.Split(stringSeparators, StringSplitOptions.None)
show result
// Split the string and return all elements with whitespace trimmed
printfn "2b) Return all elements with whitespace trimmed:"
let result = s2.Split(stringSeparators, StringSplitOptions.TrimEntries)
show result
// Split the string and return all non-empty elements
printfn "2c) Return all non-empty elements:"
let result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)
show result
// Split the string and return all non-whitespace elements with whitespace trimmed
printfn "2d) Return all non-whitespace elements with whitespace trimmed:"
let result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)
show result
// Split the string into only two elements, keeping the remainder in the last match
printfn "2e) Split into only two elements:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.None)
show result
// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
printfn "2f) Split into only two elements with whitespace trimmed:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.TrimEntries)
show result
// Split the string into only two non-empty elements, keeping the remainder in the last match
printfn "2g) Split into only two non-empty elements:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
show result
// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
printfn "2h) Split into only two non-whitespace elements with whitespace trimmed:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)
show result
(*
This example produces the following results:
1) Split a string delimited by characters:
The original string is: ",ONE,, TWO,, , THREE,,".
The delimiter character is: ','.
1a) Return all elements:
The return value contains these 9 elements:
<><ONE><>< TWO><>< >< THREE><><>
1b) Return all elements with whitespace trimmed:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>
1c) Return all non-empty elements:
The return value contains these 4 elements:
<ONE>< TWO>< >< THREE>
1d) Return all non-whitespace elements with whitespace trimmed:
The return value contains these 3 elements:
<ONE><TWO><THREE>
1e) Split into only two elements:
The return value contains these 2 elements:
<><ONE,, TWO,, , THREE,,>
1f) Split into only two elements with whitespace trimmed:
The return value contains these 2 elements:
<><ONE,, TWO,, , THREE,,>
1g) Split into only two non-empty elements:
The return value contains these 2 elements:
<ONE>< TWO,, , THREE,,>
1h) Split into only two non-whitespace elements with whitespace trimmed:
The return value contains these 2 elements:
<ONE><TWO,, , THREE,,>
2) Split a string delimited by another string:
The original string is: "[stop]ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] ".
The delimiter string is: "[stop]".
2a) Return all elements:
The return value contains these 9 elements:
<><ONE>< ><TWO ><>< ><THREE><>< >
2b) Return all elements with whitespace trimmed:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>
2c) Return all non-empty elements:
The return value contains these 6 elements:
<ONE>< ><TWO >< ><THREE>< >
2d) Return all non-whitespace elements with whitespace trimmed:
The return value contains these 3 elements:
<ONE><TWO><THREE>
2e) Split into only two elements:
The return value contains these 2 elements:
<><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] >
2f) Split into only two elements with whitespace trimmed:
The return value contains these 2 elements:
<><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop]>
2g) Split into only two non-empty elements:
The return value contains these 2 elements:
<ONE>< [stop]TWO [stop][stop] [stop]THREE[stop][stop] >
2h) Split into only two non-whitespace elements with whitespace trimmed:
The return value contains these 2 elements:
<ONE><TWO [stop][stop] [stop]THREE[stop][stop]>
*)
Public Shared Sub StringSplitOptionsExamples()
' This example demonstrates the String.Split() methods that use
' the StringSplitOptions enumeration.
' Example 1: Split a string delimited by characters
Console.WriteLine("1) Split a string delimited by characters:" & vbCrLf)
Dim s1 As String = ",ONE,, TWO,, , THREE,,"
Dim charSeparators() As Char = {","c}
Dim result() As String
Console.WriteLine("The original string is: ""{0}"".", s1)
Console.WriteLine("The delimiter character is: '{0}'." & vbCrLf, charSeparators(0))
' Split the string and return all elements
Console.WriteLine("1a) Return all elements:")
result = s1.Split(charSeparators, StringSplitOptions.None)
Show(result)
' Split the string and return all elements with whitespace trimmed
Console.WriteLine("1b) Return all elements with whitespace trimmed:")
result = s1.Split(charSeparators, StringSplitOptions.TrimEntries)
Show(result)
' Split the string and return all non-empty elements
Console.WriteLine("1c) Return all non-empty elements:")
result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries)
Show(result)
' Split the string and return all non-whitespace elements with whitespace trimmed
Console.WriteLine("1d) Return all non-whitespace elements with whitespace trimmed:")
result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries)
Show(result)
' Split the string into only two elements, keeping the remainder in the last match
Console.WriteLine("1e) Split into only two elements:")
result = s1.Split(charSeparators, 2, StringSplitOptions.None)
Show(result)
' Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("1f) Split into only two elements with whitespace trimmed:")
result = s1.Split(charSeparators, 2, StringSplitOptions.TrimEntries)
Show(result)
' Split the string into only two non-empty elements, keeping the remainder in the last match
Console.WriteLine("1g) Split into only two non-empty elements:")
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
Show(result)
' Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("1h) Split into only two non-whitespace elements with whitespace trimmed:")
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries)
Show(result)
' Example 2: Split a string delimited by another string
Console.WriteLine("2) Split a string delimited by another string:" & vbCrLf)
Dim s2 As String = "[stop]" +
"ONE[stop] [stop]" +
"TWO [stop][stop] [stop]" +
"THREE[stop][stop] "
Dim stringSeparators() As String = {"[stop]"}
Console.WriteLine("The original string is: ""{0}"".", s2)
Console.WriteLine("The delimiter string is: ""{0}""." & vbCrLf, stringSeparators(0))
' Split the string and return all elements
Console.WriteLine("2a) Return all elements:")
result = s2.Split(stringSeparators, StringSplitOptions.None)
Show(result)
' Split the string and return all elements with whitespace trimmed
Console.WriteLine("2b) Return all elements with whitespace trimmed:")
result = s2.Split(stringSeparators, StringSplitOptions.TrimEntries)
Show(result)
' Split the string and return all non-empty elements
Console.WriteLine("2c) Return all non-empty elements:")
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)
Show(result)
' Split the string and return all non-whitespace elements with whitespace trimmed
Console.WriteLine("2d) Return all non-whitespace elements with whitespace trimmed:")
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries)
Show(result)
' Split the string into only two elements, keeping the remainder in the last match
Console.WriteLine("2e) Split into only two elements:")
result = s2.Split(stringSeparators, 2, StringSplitOptions.None)
Show(result)
' Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("2f) Split into only two elements with whitespace trimmed:")
result = s2.Split(stringSeparators, 2, StringSplitOptions.TrimEntries)
Show(result)
' Split the string into only two non-empty elements, keeping the remainder in the last match
Console.WriteLine("2g) Split into only two non-empty elements:")
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
Show(result)
' Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("2h) Split into only two non-whitespace elements with whitespace trimmed:")
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries)
Show(result)
End Sub
' Display the array of separated strings.
Public Shared Sub Show(ByVal entries() As String)
Console.WriteLine("The return value contains these {0} elements:", entries.Length)
Dim entry As String
For Each entry In entries
Console.Write("<{0}>", entry)
Next entry
Console.Write(vbCrLf & vbCrLf)
End Sub
'This example produces the following results:
'
' 1) Split a string delimited by characters:
'
' The original string is: ",ONE,, TWO,, , THREE,,".
' The delimiter character is: ','.
'
' 1a) Return all elements:
' The return value contains these 9 elements:
' <><ONE><>< TWO><>< >< THREE><><>
'
' 1b) Return all elements with whitespace trimmed:
' The return value contains these 9 elements:
' <><ONE><><TWO><><><THREE><><>
'
' 1c) Return all non-empty elements:
' The return value contains these 4 elements:
' <ONE>< TWO>< >< THREE>
'
' 1d) Return all non-whitespace elements with whitespace trimmed:
' The return value contains these 3 elements:
' <ONE><TWO><THREE>
'
' 1e) Split into only two elements:
' The return value contains these 2 elements:
' <><ONE,, TWO,, , THREE,,>
'
' 1f) Split into only two elements with whitespace trimmed:
' The return value contains these 2 elements:
' <><ONE,, TWO,, , THREE,,>
'
' 1g) Split into only two non-empty elements:
' The return value contains these 2 elements:
' <ONE>< TWO,, , THREE,,>
'
' 1h) Split into only two non-whitespace elements with whitespace trimmed:
' The return value contains these 2 elements:
' <ONE><TWO,, , THREE,,>
'
' 2) Split a string delimited by another string:
'
' The original string is: "[stop]ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] ".
' The delimiter string is: "[stop]".
'
' 2a) Return all elements:
' The return value contains these 9 elements:
' <><ONE>< ><TWO ><>< ><THREE><>< >
'
' 2b) Return all elements with whitespace trimmed:
' The return value contains these 9 elements:
' <><ONE><><TWO><><><THREE><><>
'
' 2c) Return all non-empty elements:
' The return value contains these 6 elements:
' <ONE>< ><TWO >< ><THREE>< >
'
' 2d) Return all non-whitespace elements with whitespace trimmed:
' The return value contains these 3 elements:
' <ONE><TWO><THREE>
'
' 2e) Split into only two elements:
' The return value contains these 2 elements:
' <><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] >
'
' 2f) Split into only two elements with whitespace trimmed:
' The return value contains these 2 elements:
' <><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop]>
'
' 2g) Split into only two non-empty elements:
' The return value contains these 2 elements:
' <ONE>< [stop]TWO [stop][stop] [stop]THREE[stop][stop] >
'
' 2h) Split into only two non-whitespace elements with whitespace trimmed:
' The return value contains these 2 elements:
' <ONE><TWO [stop][stop] [stop]THREE[stop][stop]>
'
Açıklamalar
Sınırlayıcı karakterler döndürülen dizinin öğelerine dahil edilmez.
Bu örnek içindeki separator
karakterlerden herhangi birini içermiyorsa veya count
parametresi 1 ise, döndürülen dizi bu örneği içeren tek bir öğeden oluşur.
separator
parametre ise null
veya karakter içermiyorsa, boşluk karakterlerinin sınırlayıcı olduğu varsayılır. Boşluk karakterleri Unicode standardı tarafından tanımlanır ve Char.IsWhiteSpace yöntem, bu karaktere geçirilirse döndürür true
.
parametresini char[] separator
geçirmek null
için, çağrısının null
gibi Split(String[], Int32, StringSplitOptions)diğer bazı aşırı yüklemelerden belirsiz olmasını sağlamak için türünü belirtmeniz gerekir. Aşağıdaki örnekte, bu aşırı yükü belirsiz şekilde tanımlamanın çeşitli yolları gösterilmektedir.
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
Parametre sıfırsa veya options
parametresi ise RemoveEmptyEntries ve bu örneğin uzunluğu sıfır ise boş bir dizi döndürülür.
öğesinin separator
her öğesi ayrı bir sınırlayıcı karakteri tanımlar. options
parametresi ise Noneve iki sınırlayıcı bitişikse veya bu örneğin başında veya sonunda bir sınırlayıcı bulunursa, karşılık gelen dizi öğesi öğesini içerirEmpty.
Bu örnekte birden count
fazla alt dize varsa, dönüş değerinin ilk eksi 1 öğesinde ilk count
count
eksi 1 alt dize döndürülür ve bu örnekteki kalan karakterler dönüş değerinin son öğesinde döndürülür.
Alt dize sayısından büyükse count
, kullanılabilir alt dizeler döndürülür ve özel durum oluşturmaz.
Performansla ilgili önemli noktalar
Yöntemler döndürülen Split dizi nesnesi için bellek ve her dizi öğesi için bir String nesne ayırır. Uygulamanız en iyi performansı gerektiriyorsa veya bellek ayırmayı yönetmek uygulamanızda kritik önem taşıyorsa, dize içindeki bir alt dizeyi IndexOf bulmak için veya IndexOfAny yöntemini ve isteğe bağlı olarak Compare yöntemini kullanmayı göz önünde bulundurun.
Bir dizeyi ayırıcı karaktere bölerseniz, dizede IndexOf bir ayırıcı karakter bulmak için veya IndexOfAny yöntemini kullanın. Bir dizeyi ayırıcı dizeye bölerseniz, ayırıcı dizenin ilk karakterini bulmak için or IndexOfAny yöntemini kullanınIndexOf. Ardından, ilk karakterden sonraki karakterlerin ayırıcı dizenin kalan karakterlerine eşit olup olmadığını belirlemek için yöntemini kullanın Compare .
Ayrıca, dizeleri birden çok Split yöntem çağrısında bölmek için aynı karakter kümesi kullanılıyorsa, tek bir dizi oluşturmayı ve her yöntem çağrısında buna başvurmayı göz önünde bulundurun. Bu, her yöntem çağrısının ek yükünü önemli ölçüde azaltır.
Arayanlara Notlar
.NET Framework 3.5 ve önceki sürümlerde, yöntem bir karakter null
içeren veya içermeyen bir separator
yöntem geçirilirseSplit(Char[]), yöntem dizeyi bölmek için dizeyi kırpmak için yöntemin Trim(Char[]) kullandığından biraz farklı bir boşluk karakterleri kümesi kullanır. .NET Framework 4'den başlayarak, her iki yöntem de aynı Unicode boşluk karakterleri kümesini kullanır.
Şunlara uygulanır
Split(Char, Int32, StringSplitOptions)
- Kaynak:
- String.Manipulation.cs
- Kaynak:
- String.Manipulation.cs
- Kaynak:
- String.Manipulation.cs
Bir dizeyi belirtilen sınırlayıcı karaktere ve isteğe bağlı olarak seçeneklere göre en fazla sayıda alt dizeye böler. Sağlanan karakter ayırıcısına göre dizeyi en fazla alt dize sayısına böler ve isteğe bağlı olarak sonuçtan boş alt dizeleri atlar.
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()
Parametreler
- separator
- Char
Bu örnekteki alt dizeleri sınırlayan bir karakter.
- count
- Int32
Dizide beklenen en fazla öğe sayısı.
- options
- StringSplitOptions
Alt dizelerin kırpılıp kırpılmayacağını ve boş alt dizelerin eklenip eklenmeyeceğini belirten numaralandırma değerlerinin bit düzeyinde birleşimi.
Döndürülenler
Bu örnekten en çok count
ile sınırlandırılmış separator
alt dizeler içeren bir dizi.
Açıklamalar
Dize zaten -1 kez bölünmüşse count
, ancak dizenin sonuna ulaşılmamışsa, döndürülen dizideki son dize bu örneğin kalan kalan alt dizesini (dokunulmamış) içerecektir.
Şunlara uygulanır
Split(String[], StringSplitOptions)
- Kaynak:
- String.Manipulation.cs
- Kaynak:
- String.Manipulation.cs
- Kaynak:
- String.Manipulation.cs
Bir dizeyi belirtilen sınırlayıcı dizeye ve isteğe bağlı olarak seçeneklere göre alt dizelere böler.
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()
Parametreler
- separator
- String[]
Bu dizedeki alt dizeleri sınırlayan dize dizisi, sınırlayıcı içermeyen boş bir dizi veya null
.
- options
- StringSplitOptions
Alt dizelerin kırpılıp kırpılmayacağını ve boş alt dizelerin eklenip eklenmeyeceğini belirten numaralandırma değerlerinin bit düzeyinde birleşimi.
Döndürülenler
Öğeleri bu dizedeki alt dizeleri içeren ve içindeki bir veya daha fazla dizeyle sınırlandırılmış bir dizi separator
. Daha fazla bilgi için Açıklamalar bölümüne bakın.
- Öznitelikler
Özel durumlar
options
değerlerden StringSplitOptions biri değildir.
Örnekler
Aşağıdaki örnek, bir dizenin String.Split(String[], StringSplitOptions) yöntemini ve StringSplitOptions.RemoveEmptyEntriesparametresine options
eşit StringSplitOptions.None olarak çağırarak döndürülen dizilerdeki farkı gösterir.
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'
Aşağıdaki örnek noktalama işaretleri ve boşluk karakterleri içeren bir ayırıcı dizisini tanımlar. Yöntemine değeriyle StringSplitOptions.RemoveEmptyEntries birlikte bu diziyi Split(String[], StringSplitOptions) geçirmek, dizedeki tek tek sözcüklerden oluşan bir dizi döndürür.
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
yönteminin bağımsız değişkeni olarak ayarlanmış StringSplitOptions.RemoveEmptyEntriesolarak çağrıldığını options
unutmayın. Bu, döndürülen dizinin noktalama işaretleri ve boşluk karakterleri arasında boş alt dize eşleşmelerini temsil eden değerler içermesini String.Empty önler.
Açıklamalar
Bir dize bilinen bir dize kümesiyle sınırlandığında, alt dizelere ayırmak için yöntemini kullanabilirsiniz Split .
Sınırlayıcı dizeleri, döndürülen dizinin öğelerine dahil değildir. Örneğin, separator
dizi "--" dizesini içeriyorsa ve geçerli dize örneğinin değeri "aa--bb--cc" ise, yöntem üç öğe içeren bir dizi döndürür: "aa", "bb", ve "cc".
Bu örnek içindeki separator
dizelerden herhangi birini içermiyorsa, döndürülen dizi bu örneği içeren tek bir öğeden oluşur.
options
parametresi ise RemoveEmptyEntries ve bu örneğin uzunluğu sıfır ise, yöntemi boş bir dizi döndürür.
öğesinin separator
her öğesi, bir veya daha fazla karakterden oluşan ayrı bir sınırlayıcı tanımlar. options
bağımsız değişkeni ise Noneve iki sınırlayıcı bitişikse veya bu örneğin başında veya sonunda bir sınırlayıcı bulunursa, karşılık gelen dizi öğesi öğesini içerirString.Empty. Örneğin, "-" ve "_" olmak üzere iki öğe içeriyorsa separator
, dize örneğinin değeri "-_aa-_" ve bağımsız değişkeninin options
değeri ise Noneaşağıdaki beş öğeye sahip bir dize dizisi döndürür:
String.Empty, dizin 0'daki "-" alt dizeden önce gelen boş dizeyi temsil eder.
String.Empty, dizin 0'daki "-" alt dizesi ile dizin 1'deki "_" alt dizesi arasındaki boş dizeyi temsil eder.
"aa".
String.Empty, dizin 4'teki "-" alt dizesini izleyen boş dizeyi temsil eder.
String.Empty, dizin 5'teki "_" alt dizesini izleyen boş dizeyi temsil eder.
Ayırıcı dizi
içindeki separator
öğelerden herhangi biri birden çok karakterden oluşuyorsa, alt dizenin tamamı sınırlayıcı olarak kabul edilir. Örneğin, içindeki separator
öğelerden biri "10" ise, "This10is10a10string" dizesini bölmeye çalışmak şu dört öğeli diziyi döndürür: { "This", "is", "a", "string." }.
separator
Parametre boş olmayan dizeler null
içeriyorsa veya içeriyorsa, boşluk karakterlerinin sınırlayıcı olduğu varsayılır. Boşluk karakterleri Unicode standardı tarafından tanımlanır ve Char.IsWhiteSpace yöntem, bu karaktere geçirilirse döndürür true
.
parametresini string[] separator
geçirmek null
için, çağrısının null
gibi Split(Char[], StringSplitOptions)diğer bazı aşırı yüklemelerden belirsiz olmasını sağlamak için türünü belirtmeniz gerekir. Aşağıdaki örnekte, bu aşırı yükü belirsiz şekilde tanımlamanın çeşitli yolları gösterilmektedir.
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)
Karşılaştırma ayrıntıları
Split yöntemi, bu dizedeki parametredeki bir veya daha fazla dizeyle sınırlandırılmış alt dizeleri ayıklar separator
ve bu alt dizeleri bir dizinin öğeleri olarak döndürür.
yöntemi, Split büyük/küçük harfe duyarlı sıralı sıralama kurallarını kullanarak karşılaştırmalar yaparak sınırlayıcıları arar. Sözcük, dize ve sıralı sıralamalar hakkında daha fazla bilgi için numaralandırmaya System.Globalization.CompareOptions bakın.
yöntemi değeri Split veya boş dize ("") olan null
herhangi bir öğesini separator
yoksayar.
içindeki separator
dizelerin ortak karakterleri olduğunda belirsiz sonuçlardan kaçınmak için, Split işlem örneğin değerinin başından sonuna kadar devam eder ve örnekteki sınırlayıcıya eşit olan ilk öğeyle separator
eşleşir. Örnekte alt dizelerle karşılaşılma sırası, içindeki separator
öğelerin sırasına göre önceliklidir.
Örneğin, değeri "abcdef" olan bir örneği düşünün. içindeki separator
ilk öğe "ef" ve ikinci öğe "bcde" ise, bölme işleminin sonucu "a" ve "f" olmak üzere iki öğe içeren bir dize dizisi olur. Bunun nedeni, "bcde" örneğindeki alt dizeyle karşılaşılması ve "f" alt dizesiyle karşılaşılmadan önce içindeki separator
bir öğeyle eşleşmesidir.
Ancak, ilk öğesi separator
"bcd" ve ikinci öğesi "bc" ise, bölme işleminin sonucu "a" ve "ef" olmak üzere iki öğe içeren bir dize dizisi olur. Bunun nedeni, "bcd" öğesinin örnekteki separator
bir sınırlayıcıyla eşleşen ilk sınırlayıcı olmasıdır. Ayırıcıların sırası ters çevrildiyse ve ilk öğe "bc" ve ikinci öğe "bcd" ise, sonuç "a" ve "def" olmak üzere iki öğe içeren bir dize dizisi olur.
Performansla ilgili önemli noktalar
Yöntemler, Split döndürülen dizi nesnesi için bellek ve her dizi öğesi için bir String nesne ayırır. Uygulamanız en iyi performansı gerektiriyorsa veya uygulamanızda bellek ayırmayı yönetmek kritik önem taşıyorsa, dize içindeki bir alt dizeyi bulmak için veya IndexOfAny yöntemini ve isteğe bağlı olarak Compare yöntemini kullanmayı IndexOf göz önünde bulundurun.
Bir dizeyi ayırıcı karakterde bölüyorsanız, dizede IndexOf ayırıcı karakteri bulmak için veya IndexOfAny yöntemini kullanın. Bir dizeyi ayırıcı dizeye bölüyorsanız, ayırıcı dizenin IndexOf ilk karakterini bulmak için veya IndexOfAny yöntemini kullanın. Ardından, Compare ilk karakterden sonraki karakterlerin ayırıcı dizenin kalan karakterlerine eşit olup olmadığını belirlemek için yöntemini kullanın.
Ayrıca, dizeleri birden çok Split yöntem çağrısında bölmek için aynı karakter kümesi kullanılıyorsa, tek bir dizi oluşturmayı ve her yöntem çağrısında buna başvurmayı göz önünde bulundurun. Bu, her yöntem çağrısının ek yükünü önemli ölçüde azaltır.
Arayanlara Notlar
.NET Framework 3.5 ve önceki sürümlerde, yöntem bir karakter null
içeren veya içermeyen bir separator
yöntem geçirilirseSplit(Char[]), yöntem dizeyi bölmek için dizeyi kırpmak için yöntemin Trim(Char[]) kullandığından biraz farklı bir boşluk karakterleri kümesi kullanır. .NET Framework 4'den başlayarak, her iki yöntem de aynı Unicode boşluk karakterleri kümesini kullanır.
Şunlara uygulanır
Split(String, StringSplitOptions)
- Kaynak:
- String.Manipulation.cs
- Kaynak:
- String.Manipulation.cs
- Kaynak:
- String.Manipulation.cs
Bir dizeyi, sağlanan dize ayırıcısını temel alan alt dizelere böler.
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()
Parametreler
- separator
- String
Bu dizedeki alt dizeleri sınırlandıran bir dize.
- options
- StringSplitOptions
Alt dizelerin kırpılıp kırpılmayacağını ve boş alt dizelerin eklenip eklenmeyeceğini belirten sabit listesi değerlerinin bit düzeyinde birleşimi.
Döndürülenler
öğeleri tarafından sınırlandırılmış separator
bu örnekteki alt dizeleri içeren bir dizi.
Şunlara uygulanır
Split(Char[])
- Kaynak:
- String.Manipulation.cs
- Kaynak:
- String.Manipulation.cs
- Kaynak:
- String.Manipulation.cs
Belirtilen sınırlandırma karakterlerine göre bir dizeyi alt dizelere böler.
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()
Parametreler
- separator
- Char[]
Sınırlayıcı karakter dizisi, sınırlayıcı içermeyen boş bir dizi veya null
.
Döndürülenler
öğeleri içinde bir veya daha fazla karakterle separator
sınırlandırılmış bu örnekteki alt dizeleri içeren bir dizi. Daha fazla bilgi için Açıklamalar bölümüne bakın.
Örnekler
Aşağıdaki örnek, boşluk karakterini () ve sekme karakterini\t
(
) sınırlayıcı olarak değerlendirerek metin bloğundan tek tek sözcükleri ayıklamayı gösterir. Bölünen dize bu karakterlerin ikisini de içerir.
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
Açıklamalar
Bir dize bilinen bir karakter kümesiyle sınırlandırıldığında, alt dizelere ayırmak için yöntemini kullanabilirsiniz Split(Char[]) .
Sınırlayıcı karakterler döndürülen dizinin öğelerine dahil edilmez. Örneğin, ayırıcı dizi "-" karakterini içeriyorsa ve geçerli dize örneğinin değeri "aa-bb-cc" ise, yöntem üç öğe içeren bir dizi döndürür: "aa", "bb", ve "cc".
Bu örnek içindeki separator
karakterlerden herhangi birini içermiyorsa, döndürülen dizi bu örneği içeren tek bir öğeden oluşur.
öğesinin separator
her öğesi ayrı bir sınırlayıcı karakteri tanımlar. İki sınırlayıcı bitişikse veya bu örneğin başında veya sonunda bir sınırlayıcı bulunursa, döndürülen dizideki ilgili öğe içerir Empty.
Aşağıdaki tabloda bazı örnekler gösterilmektedir.
Dil | Dize değeri | Ayırıcı | Döndürülen dizi |
---|---|---|---|
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# | "Muz" | new Char[] {'.'} | {"Banana"} |
Visual Basic | "Muz" | Char() = {"." c} | {"Banana"} |
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"} |
Ayırıcı dizi
Ayırıcının her öğesi, tek bir karakterden oluşan ayrı bir sınırlayıcı tanımlar.
separator
Bağımsız değişken karakter null
ise veya karakter içermiyorsa, yöntem boşluk karakterlerini sınırlayıcı olarak ele alır. Boşluk karakterleri Unicode standardı tarafından tanımlanır ve Char.IsWhiteSpace yöntem, buna bir boşluk karakteri geçirilirse döndürür true
.
String.Split(Char[]) ve derleyici aşırı yükleme çözümlemesi
bu aşırı yüklemesinin String.Split tek parametresi bir karakter dizisi olsa da, aşağıdaki örnekte gösterildiği gibi tek bir karakterle çağırabilirsiniz.
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.
parametresi özniteliğiyle süslendiğinden separator
ParamArrayAttribute , derleyiciler tek bir karakteri tek öğeli karakter dizisi olarak yorumlar. Bu, parametre içeren separator
diğer String.Split aşırı yüklemeler için geçerli değildir; bu aşırı yüklemeleri bağımsız değişken olarak bir karakter dizisini separator
açıkça geçirmeniz gerekir.
Karşılaştırma ayrıntıları
Split(Char[]) yöntemi, bu dizedeki bir veya daha fazla karakterle separator
sınırlandırılmış alt dizeleri ayıklar ve bu alt dizeleri bir dizinin öğeleri olarak döndürür.
yöntemi, Split(Char[]) büyük/küçük harfe duyarlı sıralı sıralama kurallarını kullanarak karşılaştırmalar yaparak sınırlayıcıları arar. Sözcük, dize ve sıralı sıralamalar hakkında daha fazla bilgi için numaralandırmaya System.Globalization.CompareOptions bakın.
Performansla ilgili önemli noktalar
Yöntemler, Split döndürülen dizi nesnesi için bellek ve her dizi öğesi için bir String nesne ayırır. Uygulamanız en iyi performansı gerektiriyorsa veya uygulamanızda bellek ayırmayı yönetmek kritik önem taşıyorsa veya IndexOfAny yöntemini kullanmayı IndexOf göz önünde bulundurun. Ayrıca bir dize içindeki alt dizeyi Compare bulmak için yöntemini kullanma seçeneğiniz de vardır.
Bir dizeyi ayırıcı karakterde bölmek için, dizede IndexOf ayırıcı karakteri bulmak için veya IndexOfAny yöntemini kullanın. Ayırıcı dizedeki bir dizeyi bölmek için, ayırıcı dizenin ilk karakterini bulmak için veya IndexOfAny yöntemini kullanınIndexOf. Ardından, Compare ilk karakterden sonraki karakterlerin ayırıcı dizenin kalan karakterlerine eşit olup olmadığını belirlemek için yöntemini kullanın.
Ayrıca, dizeleri birden çok Split yöntem çağrısında bölmek için aynı karakter kümesi kullanılıyorsa, tek bir dizi oluşturmayı ve her yöntem çağrısında buna başvurmayı göz önünde bulundurun. Bu, her yöntem çağrısının ek yükünü önemli ölçüde azaltır.
Arayanlara Notlar
.NET Framework 3.5 ve önceki sürümlerde, yöntem karakter içermeyen veya karakter içermeyen bir null
separator
yönteme geçirilirseSplit(Char[]), yöntem dizeyi bölmek için, yöntemin dizeyi kırpmak için kullandığından Trim(Char[]) biraz farklı bir boşluk karakterleri kümesi kullanır. .NET Framework 4'den başlayarak, her iki yöntem de aynı Unicode boşluk karakterleri kümesini kullanır.
Ayrıca bkz.
- Char
- Concat(Object)
- Insert(Int32, String)
- Join(String, String[])
- Remove(Int32, Int32)
- Replace(Char, Char)
- Substring(Int32)
- Trim(Char[])
Şunlara uygulanır
Split(Char[], Int32)
- Kaynak:
- String.Manipulation.cs
- Kaynak:
- String.Manipulation.cs
- Kaynak:
- String.Manipulation.cs
Bir dizeyi belirtilen sınırlayıcı karakterlere göre en fazla sayıda alt dizeye böler.
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()
Parametreler
- separator
- Char[]
Bu dizedeki alt dizeleri sınırlandıran bir karakter dizisi, sınırlayıcı içermeyen boş bir dizi veya null
.
- count
- Int32
Döndürülecek en fazla alt dize sayısı.
Döndürülenler
Bu örnekteki öğeleri içinde bir veya daha fazla karakterle separator
sınırlandırılmış alt dizeler içeren bir dizi. Daha fazla bilgi için Açıklamalar bölümüne bakın.
Özel durumlar
count
negatiftir.
Örnekler
Aşağıdaki örnek tarafından Splitdöndürülen dize sayısını sınırlamak için nasıl count
kullanılabileceğini gösterir.
string name = "Alex Johnson III";
string[] subs = name.Split(null, 2);
string firstName = subs[0];
string lastName;
if (subs.Length > 1)
{
lastName = subs[1];
}
// firstName = "Alex"
// lastName = "Johnson III"
let name = "Alex Johnson III"
let subs = name.Split(null, 2)
let firstName = subs[0]
let lastName =
if subs.Length > 1 then
subs[1]
else
""
// firstName = "Alex"
// lastName = "Johnson III"
Console.WriteLine("What is your name?")
Dim name As String = Console.ReadLine()
Dim substrings = name.Split(" "c, count:=2)
Dim firstName As String = substrings(0)
Dim lastName As String
If substrings.Length > 1 Then
lastName = substrings(1)
End If
Console.WriteLine("firstName = ""{0}""", firstName)
Console.WriteLine("lastName = ""{0}""", lastName)
' If the user enters "Alex Johnson III":
' firstName = "Alex"
' lastName = "Johnson III"
Açıklamalar
Sınırlayıcı karakterler döndürülen dizinin öğelerine dahil edilmez.
Bu örnek içindeki separator
karakterlerden herhangi birini içermiyorsa, döndürülen dizi bu örneği içeren tek bir öğeden oluşur. Sıfır ise count
, boş bir dizi döndürülür.
separator
Parametre karakter null
içeriyorsa veya karakter içermiyorsa, boşluk karakterlerinin sınırlayıcı olduğu varsayılır. Boşluk karakterleri Unicode standardı tarafından tanımlanır ve Char.IsWhiteSpace yöntem, bu karaktere geçirilirse döndürür true
.
öğesinin separator
her öğesi ayrı bir sınırlayıcı karakteri tanımlar. İki sınırlayıcı bitişikse veya bu örneğin başında veya sonunda bir sınırlayıcı bulunursa, karşılık gelen dizi öğesi içerir Empty.
Bu örnekte birden count
fazla alt dize varsa, dönüş değerinin ilk öğelerinde ilk count - 1
count - 1
alt dizeler döndürülür ve bu örnekteki kalan karakterler dönüş değerinin son öğesinde döndürülür.
Alt dize sayısından büyükse count
, kullanılabilir alt dizeler döndürülür ve özel durum oluşturmaz.
Aşağıdaki tabloda bazı örnekler gösterilmektedir.
Dil | Dize değeri | Ayırıcı | Döndürülen dizi |
---|---|---|---|
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# | "Muz" | new Char[] {'.'} | {"Banana"} |
Visual Basic | "Muz" | Char() = {"." c} | {"Banana"} |
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"} |
Performansla ilgili önemli noktalar
Yöntemler, Split döndürülen dizi nesnesi için bellek ve her dizi öğesi için bir String nesne ayırır. Uygulamanız en iyi performansı gerektiriyorsa veya uygulamanızda bellek ayırmayı yönetmek kritik önem taşıyorsa, dize içindeki bir alt dizeyi bulmak için veya IndexOfAny yöntemini ve isteğe bağlı olarak Compare yöntemini kullanmayı IndexOf göz önünde bulundurun.
Bir dizeyi ayırıcı karakterde bölüyorsanız, dizede IndexOf ayırıcı karakteri bulmak için veya IndexOfAny yöntemini kullanın. Bir dizeyi ayırıcı dizeye bölüyorsanız, ayırıcı dizenin IndexOf ilk karakterini bulmak için veya IndexOfAny yöntemini kullanın. Ardından, Compare ilk karakterden sonraki karakterlerin ayırıcı dizenin kalan karakterlerine eşit olup olmadığını belirlemek için yöntemini kullanın.
Ayrıca, dizeleri birden çok Split yöntem çağrısında bölmek için aynı karakter kümesi kullanılıyorsa, tek bir dizi oluşturmayı ve her yöntem çağrısında buna başvurmayı göz önünde bulundurun. Bu, her yöntem çağrısının ek yükünü önemli ölçüde azaltır.
Arayanlara Notlar
.NET Framework 3.5 ve önceki sürümlerde, yöntem karakter içermeyen veya karakter içermeyen bir null
separator
yönteme geçirilirseSplit(Char[]), yöntem dizeyi bölmek için, yöntemin dizeyi kırpmak için kullandığından Trim(Char[]) biraz farklı bir boşluk karakterleri kümesi kullanır. .NET Framework 4'den başlayarak, her iki yöntem de aynı Unicode boşluk karakterleri kümesini kullanır.
Ayrıca bkz.
- Char
- Array
- Int32
- Concat(Object)
- Insert(Int32, String)
- Join(String, String[])
- Remove(Int32, Int32)
- Replace(Char, Char)
- Substring(Int32)
- Trim(Char[])
Şunlara uygulanır
Split(Char, StringSplitOptions)
- Kaynak:
- String.Manipulation.cs
- Kaynak:
- String.Manipulation.cs
- Kaynak:
- String.Manipulation.cs
Bir dizeyi belirtilen sınırlayıcı karaktere ve isteğe bağlı olarak seçeneklere göre alt dizelere böler.
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()
Parametreler
- separator
- Char
Bu dizedeki alt dizeleri sınırlandıran bir karakter.
- options
- StringSplitOptions
Alt dizelerin kırpılıp kırpılmayacağını ve boş alt dizelerin eklenip eklenmeyeceğini belirten sabit listesi değerlerinin bit düzeyinde birleşimi.
Döndürülenler
öğeleri tarafından sınırlandırılmış separator
bu örnekteki alt dizeleri içeren bir dizi.
Şunlara uygulanır
Split(ReadOnlySpan<Char>)
public:
cli::array <System::String ^> ^ Split(ReadOnlySpan<char> separator);
public string[] Split (scoped ReadOnlySpan<char> separator);
member this.Split : ReadOnlySpan<char> -> string[]
Public Function Split (separator As ReadOnlySpan(Of Char)) As String()
Parametreler
- separator
- ReadOnlySpan<Char>
Döndürülenler
Şunlara uygulanır
Split(String[], Int32, StringSplitOptions)
- Kaynak:
- String.Manipulation.cs
- Kaynak:
- String.Manipulation.cs
- Kaynak:
- String.Manipulation.cs
Belirtilen sınırlayıcı dizeleri ve isteğe bağlı olarak seçenekleri temel alarak bir dizeyi en fazla sayıda alt dizeye böler.
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()
Parametreler
- separator
- String[]
Bu dizedeki alt dizeleri sınırlandıran dizeler, sınırlayıcı içermeyen boş bir dizi veya null
.
- count
- Int32
Döndürülecek en fazla alt dize sayısı.
- options
- StringSplitOptions
Alt dizelerin kırpılıp kırpılmayacağını ve boş alt dizelerin eklenip eklenmeyeceğini belirten sabit listesi değerlerinin bit düzeyinde birleşimi.
Döndürülenler
Öğeleri bu dizedeki alt dizeleri içeren ve içindeki bir veya daha fazla dizeyle sınırlandırılmış bir dizi separator
. Daha fazla bilgi için Açıklamalar bölümüne bakın.
- Öznitelikler
Özel durumlar
count
negatiftir.
options
değerlerden biri StringSplitOptions değildir.
Örnekler
Aşağıdaki örnek, yöntemi tarafından oluşturulan alt dizeleri dahil etmek veya hariç tutmak için numaralandırmayı Split kullanırStringSplitOptions.
// 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.
// Example 1: Split a string delimited by characters
Console.WriteLine("1) Split a string delimited by characters:\n");
string s1 = ",ONE,, TWO,, , THREE,,";
char[] charSeparators = new char[] { ',' };
string[] result;
Console.WriteLine($"The original string is: \"{s1}\".");
Console.WriteLine($"The delimiter character is: '{charSeparators[0]}'.\n");
// Split the string and return all elements
Console.WriteLine("1a) Return all elements:");
result = s1.Split(charSeparators, StringSplitOptions.None);
Show(result);
// Split the string and return all elements with whitespace trimmed
Console.WriteLine("1b) Return all elements with whitespace trimmed:");
result = s1.Split(charSeparators, StringSplitOptions.TrimEntries);
Show(result);
// Split the string and return all non-empty elements
Console.WriteLine("1c) Return all non-empty elements:");
result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// Split the string and return all non-whitespace elements with whitespace trimmed
Console.WriteLine("1d) Return all non-whitespace elements with whitespace trimmed:");
result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
Show(result);
// Split the string into only two elements, keeping the remainder in the last match
Console.WriteLine("1e) Split into only two elements:");
result = s1.Split(charSeparators, 2, StringSplitOptions.None);
Show(result);
// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("1f) Split into only two elements with whitespace trimmed:");
result = s1.Split(charSeparators, 2, StringSplitOptions.TrimEntries);
Show(result);
// Split the string into only two non-empty elements, keeping the remainder in the last match
Console.WriteLine("1g) Split into only two non-empty elements:");
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("1h) Split into only two non-whitespace elements with whitespace trimmed:");
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
Show(result);
// Example 2: Split a string delimited by another string
Console.WriteLine("2) Split a string delimited by another string:\n");
string s2 = "[stop]" +
"ONE[stop] [stop]" +
"TWO [stop][stop] [stop]" +
"THREE[stop][stop] ";
string[] stringSeparators = new string[] { "[stop]" };
Console.WriteLine($"The original string is: \"{s2}\".");
Console.WriteLine($"The delimiter string is: \"{stringSeparators[0]}\".\n");
// Split the string and return all elements
Console.WriteLine("2a) Return all elements:");
result = s2.Split(stringSeparators, StringSplitOptions.None);
Show(result);
// Split the string and return all elements with whitespace trimmed
Console.WriteLine("2b) Return all elements with whitespace trimmed:");
result = s2.Split(stringSeparators, StringSplitOptions.TrimEntries);
Show(result);
// Split the string and return all non-empty elements
Console.WriteLine("2c) Return all non-empty elements:");
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// Split the string and return all non-whitespace elements with whitespace trimmed
Console.WriteLine("2d) Return all non-whitespace elements with whitespace trimmed:");
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
Show(result);
// Split the string into only two elements, keeping the remainder in the last match
Console.WriteLine("2e) Split into only two elements:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.None);
Show(result);
// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("2f) Split into only two elements with whitespace trimmed:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.TrimEntries);
Show(result);
// Split the string into only two non-empty elements, keeping the remainder in the last match
Console.WriteLine("2g) Split into only two non-empty elements:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("2h) Split into only two non-whitespace elements with whitespace trimmed:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
Show(result);
// Display the array of separated strings using a local function
void Show(string[] entries)
{
Console.WriteLine($"The return value contains these {entries.Length} elements:");
foreach (string entry in entries)
{
Console.Write($"<{entry}>");
}
Console.Write("\n\n");
}
/*
This example produces the following results:
1) Split a string delimited by characters:
The original string is: ",ONE,, TWO,, , THREE,,".
The delimiter character is: ','.
1a) Return all elements:
The return value contains these 9 elements:
<><ONE><>< TWO><>< >< THREE><><>
1b) Return all elements with whitespace trimmed:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>
1c) Return all non-empty elements:
The return value contains these 4 elements:
<ONE>< TWO>< >< THREE>
1d) Return all non-whitespace elements with whitespace trimmed:
The return value contains these 3 elements:
<ONE><TWO><THREE>
1e) Split into only two elements:
The return value contains these 2 elements:
<><ONE,, TWO,, , THREE,,>
1f) Split into only two elements with whitespace trimmed:
The return value contains these 2 elements:
<><ONE,, TWO,, , THREE,,>
1g) Split into only two non-empty elements:
The return value contains these 2 elements:
<ONE>< TWO,, , THREE,,>
1h) Split into only two non-whitespace elements with whitespace trimmed:
The return value contains these 2 elements:
<ONE><TWO,, , THREE,,>
2) Split a string delimited by another string:
The original string is: "[stop]ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] ".
The delimiter string is: "[stop]".
2a) Return all elements:
The return value contains these 9 elements:
<><ONE>< ><TWO ><>< ><THREE><>< >
2b) Return all elements with whitespace trimmed:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>
2c) Return all non-empty elements:
The return value contains these 6 elements:
<ONE>< ><TWO >< ><THREE>< >
2d) Return all non-whitespace elements with whitespace trimmed:
The return value contains these 3 elements:
<ONE><TWO><THREE>
2e) Split into only two elements:
The return value contains these 2 elements:
<><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] >
2f) Split into only two elements with whitespace trimmed:
The return value contains these 2 elements:
<><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop]>
2g) Split into only two non-empty elements:
The return value contains these 2 elements:
<ONE>< [stop]TWO [stop][stop] [stop]THREE[stop][stop] >
2h) Split into only two non-whitespace elements with whitespace trimmed:
The return value contains these 2 elements:
<ONE><TWO [stop][stop] [stop]THREE[stop][stop]>
*/
// This example demonstrates the String.Split() methods that use
// the StringSplitOptions enumeration.
// Display the array of separated strings using a local function
let show (entries: string[]) =
printfn $"The return value contains these {entries.Length} elements:"
for entry in entries do
printf $"<{entry}>"
printf "\n\n"
// Example 1: Split a string delimited by characters
printfn "1) Split a string delimited by characters:\n"
let s1 = ",ONE,, TWO,, , THREE,,"
let charSeparators = [| ',' |]
printfn $"The original string is: \"{s1}\"."
printfn $"The delimiter character is: '{charSeparators[0]}'.\n"
// Split the string and return all elements
printfn "1a) Return all elements:"
let result = s1.Split(charSeparators, StringSplitOptions.None)
show result
// Split the string and return all elements with whitespace trimmed
printfn "1b) Return all elements with whitespace trimmed:"
let result = s1.Split(charSeparators, StringSplitOptions.TrimEntries)
show result
// Split the string and return all non-empty elements
printfn "1c) Return all non-empty elements:"
let result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries)
show result
// Split the string and return all non-whitespace elements with whitespace trimmed
printfn "1d) Return all non-whitespace elements with whitespace trimmed:"
let result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)
show result
// Split the string into only two elements, keeping the remainder in the last match
printfn "1e) Split into only two elements:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.None)
show result
// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
printfn "1f) Split into only two elements with whitespace trimmed:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.TrimEntries)
show result
// Split the string into only two non-empty elements, keeping the remainder in the last match
printfn "1g) Split into only two non-empty elements:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
show result
// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
printfn "1h) Split into only two non-whitespace elements with whitespace trimmed:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)
show result
// Example 2: Split a string delimited by another string
printfn "2) Split a string delimited by another string:\n"
let s2 = "[stop]" +
"ONE[stop] [stop]" +
"TWO [stop][stop] [stop]" +
"THREE[stop][stop] "
let stringSeparators = [| "[stop]" |]
printfn $"The original string is: \"{s2}\"."
printfn $"The delimiter string is: \"{stringSeparators[0]}\".\n"
// Split the string and return all elements
printfn "2a) Return all elements:"
let result = s2.Split(stringSeparators, StringSplitOptions.None)
show result
// Split the string and return all elements with whitespace trimmed
printfn "2b) Return all elements with whitespace trimmed:"
let result = s2.Split(stringSeparators, StringSplitOptions.TrimEntries)
show result
// Split the string and return all non-empty elements
printfn "2c) Return all non-empty elements:"
let result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)
show result
// Split the string and return all non-whitespace elements with whitespace trimmed
printfn "2d) Return all non-whitespace elements with whitespace trimmed:"
let result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)
show result
// Split the string into only two elements, keeping the remainder in the last match
printfn "2e) Split into only two elements:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.None)
show result
// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
printfn "2f) Split into only two elements with whitespace trimmed:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.TrimEntries)
show result
// Split the string into only two non-empty elements, keeping the remainder in the last match
printfn "2g) Split into only two non-empty elements:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
show result
// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
printfn "2h) Split into only two non-whitespace elements with whitespace trimmed:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)
show result
(*
This example produces the following results:
1) Split a string delimited by characters:
The original string is: ",ONE,, TWO,, , THREE,,".
The delimiter character is: ','.
1a) Return all elements:
The return value contains these 9 elements:
<><ONE><>< TWO><>< >< THREE><><>
1b) Return all elements with whitespace trimmed:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>
1c) Return all non-empty elements:
The return value contains these 4 elements:
<ONE>< TWO>< >< THREE>
1d) Return all non-whitespace elements with whitespace trimmed:
The return value contains these 3 elements:
<ONE><TWO><THREE>
1e) Split into only two elements:
The return value contains these 2 elements:
<><ONE,, TWO,, , THREE,,>
1f) Split into only two elements with whitespace trimmed:
The return value contains these 2 elements:
<><ONE,, TWO,, , THREE,,>
1g) Split into only two non-empty elements:
The return value contains these 2 elements:
<ONE>< TWO,, , THREE,,>
1h) Split into only two non-whitespace elements with whitespace trimmed:
The return value contains these 2 elements:
<ONE><TWO,, , THREE,,>
2) Split a string delimited by another string:
The original string is: "[stop]ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] ".
The delimiter string is: "[stop]".
2a) Return all elements:
The return value contains these 9 elements:
<><ONE>< ><TWO ><>< ><THREE><>< >
2b) Return all elements with whitespace trimmed:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>
2c) Return all non-empty elements:
The return value contains these 6 elements:
<ONE>< ><TWO >< ><THREE>< >
2d) Return all non-whitespace elements with whitespace trimmed:
The return value contains these 3 elements:
<ONE><TWO><THREE>
2e) Split into only two elements:
The return value contains these 2 elements:
<><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] >
2f) Split into only two elements with whitespace trimmed:
The return value contains these 2 elements:
<><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop]>
2g) Split into only two non-empty elements:
The return value contains these 2 elements:
<ONE>< [stop]TWO [stop][stop] [stop]THREE[stop][stop] >
2h) Split into only two non-whitespace elements with whitespace trimmed:
The return value contains these 2 elements:
<ONE><TWO [stop][stop] [stop]THREE[stop][stop]>
*)
Public Shared Sub StringSplitOptionsExamples()
' This example demonstrates the String.Split() methods that use
' the StringSplitOptions enumeration.
' Example 1: Split a string delimited by characters
Console.WriteLine("1) Split a string delimited by characters:" & vbCrLf)
Dim s1 As String = ",ONE,, TWO,, , THREE,,"
Dim charSeparators() As Char = {","c}
Dim result() As String
Console.WriteLine("The original string is: ""{0}"".", s1)
Console.WriteLine("The delimiter character is: '{0}'." & vbCrLf, charSeparators(0))
' Split the string and return all elements
Console.WriteLine("1a) Return all elements:")
result = s1.Split(charSeparators, StringSplitOptions.None)
Show(result)
' Split the string and return all elements with whitespace trimmed
Console.WriteLine("1b) Return all elements with whitespace trimmed:")
result = s1.Split(charSeparators, StringSplitOptions.TrimEntries)
Show(result)
' Split the string and return all non-empty elements
Console.WriteLine("1c) Return all non-empty elements:")
result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries)
Show(result)
' Split the string and return all non-whitespace elements with whitespace trimmed
Console.WriteLine("1d) Return all non-whitespace elements with whitespace trimmed:")
result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries)
Show(result)
' Split the string into only two elements, keeping the remainder in the last match
Console.WriteLine("1e) Split into only two elements:")
result = s1.Split(charSeparators, 2, StringSplitOptions.None)
Show(result)
' Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("1f) Split into only two elements with whitespace trimmed:")
result = s1.Split(charSeparators, 2, StringSplitOptions.TrimEntries)
Show(result)
' Split the string into only two non-empty elements, keeping the remainder in the last match
Console.WriteLine("1g) Split into only two non-empty elements:")
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
Show(result)
' Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("1h) Split into only two non-whitespace elements with whitespace trimmed:")
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries)
Show(result)
' Example 2: Split a string delimited by another string
Console.WriteLine("2) Split a string delimited by another string:" & vbCrLf)
Dim s2 As String = "[stop]" +
"ONE[stop] [stop]" +
"TWO [stop][stop] [stop]" +
"THREE[stop][stop] "
Dim stringSeparators() As String = {"[stop]"}
Console.WriteLine("The original string is: ""{0}"".", s2)
Console.WriteLine("The delimiter string is: ""{0}""." & vbCrLf, stringSeparators(0))
' Split the string and return all elements
Console.WriteLine("2a) Return all elements:")
result = s2.Split(stringSeparators, StringSplitOptions.None)
Show(result)
' Split the string and return all elements with whitespace trimmed
Console.WriteLine("2b) Return all elements with whitespace trimmed:")
result = s2.Split(stringSeparators, StringSplitOptions.TrimEntries)
Show(result)
' Split the string and return all non-empty elements
Console.WriteLine("2c) Return all non-empty elements:")
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)
Show(result)
' Split the string and return all non-whitespace elements with whitespace trimmed
Console.WriteLine("2d) Return all non-whitespace elements with whitespace trimmed:")
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries)
Show(result)
' Split the string into only two elements, keeping the remainder in the last match
Console.WriteLine("2e) Split into only two elements:")
result = s2.Split(stringSeparators, 2, StringSplitOptions.None)
Show(result)
' Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("2f) Split into only two elements with whitespace trimmed:")
result = s2.Split(stringSeparators, 2, StringSplitOptions.TrimEntries)
Show(result)
' Split the string into only two non-empty elements, keeping the remainder in the last match
Console.WriteLine("2g) Split into only two non-empty elements:")
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
Show(result)
' Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("2h) Split into only two non-whitespace elements with whitespace trimmed:")
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries)
Show(result)
End Sub
' Display the array of separated strings.
Public Shared Sub Show(ByVal entries() As String)
Console.WriteLine("The return value contains these {0} elements:", entries.Length)
Dim entry As String
For Each entry In entries
Console.Write("<{0}>", entry)
Next entry
Console.Write(vbCrLf & vbCrLf)
End Sub
'This example produces the following results:
'
' 1) Split a string delimited by characters:
'
' The original string is: ",ONE,, TWO,, , THREE,,".
' The delimiter character is: ','.
'
' 1a) Return all elements:
' The return value contains these 9 elements:
' <><ONE><>< TWO><>< >< THREE><><>
'
' 1b) Return all elements with whitespace trimmed:
' The return value contains these 9 elements:
' <><ONE><><TWO><><><THREE><><>
'
' 1c) Return all non-empty elements:
' The return value contains these 4 elements:
' <ONE>< TWO>< >< THREE>
'
' 1d) Return all non-whitespace elements with whitespace trimmed:
' The return value contains these 3 elements:
' <ONE><TWO><THREE>
'
' 1e) Split into only two elements:
' The return value contains these 2 elements:
' <><ONE,, TWO,, , THREE,,>
'
' 1f) Split into only two elements with whitespace trimmed:
' The return value contains these 2 elements:
' <><ONE,, TWO,, , THREE,,>
'
' 1g) Split into only two non-empty elements:
' The return value contains these 2 elements:
' <ONE>< TWO,, , THREE,,>
'
' 1h) Split into only two non-whitespace elements with whitespace trimmed:
' The return value contains these 2 elements:
' <ONE><TWO,, , THREE,,>
'
' 2) Split a string delimited by another string:
'
' The original string is: "[stop]ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] ".
' The delimiter string is: "[stop]".
'
' 2a) Return all elements:
' The return value contains these 9 elements:
' <><ONE>< ><TWO ><>< ><THREE><>< >
'
' 2b) Return all elements with whitespace trimmed:
' The return value contains these 9 elements:
' <><ONE><><TWO><><><THREE><><>
'
' 2c) Return all non-empty elements:
' The return value contains these 6 elements:
' <ONE>< ><TWO >< ><THREE>< >
'
' 2d) Return all non-whitespace elements with whitespace trimmed:
' The return value contains these 3 elements:
' <ONE><TWO><THREE>
'
' 2e) Split into only two elements:
' The return value contains these 2 elements:
' <><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] >
'
' 2f) Split into only two elements with whitespace trimmed:
' The return value contains these 2 elements:
' <><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop]>
'
' 2g) Split into only two non-empty elements:
' The return value contains these 2 elements:
' <ONE>< [stop]TWO [stop][stop] [stop]THREE[stop][stop] >
'
' 2h) Split into only two non-whitespace elements with whitespace trimmed:
' The return value contains these 2 elements:
' <ONE><TWO [stop][stop] [stop]THREE[stop][stop]>
'
Açıklamalar
Sınırlayıcı dizeleri, döndürülen dizinin öğelerine dahil değildir.
Bu örnek içinde separator
dizelerden herhangi birini içermiyorsa veya count
parametresi 1 ise, döndürülen dizi bu örneği içeren tek bir öğeden oluşur.
separator
Parametre karakter null
içeriyorsa veya karakter içermiyorsa, boşluk karakterlerinin sınırlayıcı olduğu varsayılır. Boşluk karakterleri Unicode standardı tarafından tanımlanır ve Char.IsWhiteSpace yöntem, bu karaktere geçirilirse döndürür true
.
parametresini string[] separator
geçirmek null
için, çağrısının null
gibi Split(Char[], Int32, StringSplitOptions)diğer bazı aşırı yüklemelerden belirsiz olmasını sağlamak için türünü belirtmeniz gerekir. Aşağıdaki örnekte, bu aşırı yükü belirsiz şekilde tanımlamanın çeşitli yolları gösterilmektedir.
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
Parametre sıfırsa veya options
parametre ise RemoveEmptyEntries ve bu örneğin uzunluğu sıfırsa boş bir dizi döndürülür.
öğesinin separator
her öğesi, bir veya daha fazla karakterden oluşan ayrı bir sınırlayıcı tanımlar. options
parametresi ise Noneve iki sınırlayıcı bitişikse veya bu örneğin başında veya sonunda bir sınırlayıcı bulunursa, ilgili dizi öğesi öğesini içerirEmpty.
Bu örnekte birden fazla count
alt dize varsa, döndürülen değerin ilk eksi 1 öğesinde ilk count
count
eksi 1 alt dize döndürülür ve bu örnekteki kalan karakterler dönüş değerinin son öğesinde döndürülür.
Alt dize sayısından büyükse count
, kullanılabilir alt dizeler döndürülür ve özel durum oluşturmaz.
Ayırıcı dizi
içindeki separator
öğelerden herhangi biri birden çok karakterden oluşuyorsa, alt dizenin tamamı sınırlayıcı olarak kabul edilir. Örneğin, içindeki separator
öğelerden biri "10" ise, "This10is10a10string" dizesini bölmeye çalışmak şu dört öğeli diziyi döndürür: { "This", "is", "a", "string." }.
Karşılaştırma ayrıntıları
Split yöntemi, bu dizedeki parametredeki bir veya daha fazla dizeyle sınırlandırılmış alt dizeleri ayıklar separator
ve bu alt dizeleri bir dizinin öğeleri olarak döndürür.
yöntemi, Split büyük/küçük harfe duyarlı sıralı sıralama kurallarını kullanarak karşılaştırmalar yaparak sınırlayıcıları arar. Sözcük, dize ve sıralı sıralamalar hakkında daha fazla bilgi için numaralandırmaya System.Globalization.CompareOptions bakın.
yöntemi değeri Split veya boş dize ("") olan null
herhangi bir öğesini separator
yoksayar.
içindeki separator
dizelerin ortak karakterleri olduğunda belirsiz sonuçlardan kaçınmak için yöntem, Split örneğin değerinin başından sonuna kadar ilerler ve örnekteki sınırlayıcıya eşit olan ilk öğeyle separator
eşleşir. Örnekte alt dizelerle karşılaşılma sırası, içindeki separator
öğelerin sırasına göre önceliklidir.
Örneğin, değeri "abcdef" olan bir örneği düşünün. içindeki separator
ilk öğe "ef" ve ikinci öğe "bcde" ise bölme işleminin sonucu "a" ve "f" olur. Bunun nedeni, "bcde" örneğindeki alt dizeyle karşılaşılması ve "f" alt dizesiyle karşılaşılmadan önce içindeki separator
bir öğeyle eşleşmesidir.
Ancak, ilk öğesi separator
"bcd" ve ikinci öğesi "bc" ise bölme işleminin sonucu "a" ve "ef" olur. Bunun nedeni, "bcd" öğesinin örnekteki separator
bir sınırlayıcıyla eşleşen ilk sınırlayıcı olmasıdır. Ayırıcıların sırası ters çevrildiyse ve ilk öğe "bc" ve ikinci öğe "bcd" ise sonuç "a" ve "def" olur.
Performansla ilgili önemli noktalar
Yöntemler, Split döndürülen dizi nesnesi için bellek ve her dizi öğesi için bir String nesne ayırır. Uygulamanız en iyi performansı gerektiriyorsa veya uygulamanızda bellek ayırmayı yönetmek kritik önem taşıyorsa, dize içindeki bir alt dizeyi bulmak için veya IndexOfAny yöntemini ve isteğe bağlı olarak Compare yöntemini kullanmayı IndexOf göz önünde bulundurun.
Bir dizeyi ayırıcı karakterde bölüyorsanız, dizede IndexOf ayırıcı karakteri bulmak için veya IndexOfAny yöntemini kullanın. Bir dizeyi ayırıcı dizeye bölüyorsanız, ayırıcı dizenin IndexOf ilk karakterini bulmak için veya IndexOfAny yöntemini kullanın. Ardından, Compare ilk karakterden sonraki karakterlerin ayırıcı dizenin kalan karakterlerine eşit olup olmadığını belirlemek için yöntemini kullanın.
Ayrıca, dizeleri birden çok Split yöntem çağrısında bölmek için aynı karakter kümesi kullanılıyorsa, tek bir dizi oluşturmayı ve her yöntem çağrısında buna başvurmayı göz önünde bulundurun. Bu, her yöntem çağrısının ek yükünü önemli ölçüde azaltır.
Arayanlara Notlar
.NET Framework 3.5 ve önceki sürümlerde, yöntem karakter içermeyen veya karakter içermeyen bir null
separator
yönteme geçirilirseSplit(Char[]), yöntem dizeyi bölmek için, yöntemin dizeyi kırpmak için kullandığından Trim(Char[]) biraz farklı bir boşluk karakterleri kümesi kullanır. .NET Framework 4'den başlayarak, her iki yöntem de aynı Unicode boşluk karakterleri kümesini kullanır.
Şunlara uygulanır
Split(Char[], StringSplitOptions)
- Kaynak:
- String.Manipulation.cs
- Kaynak:
- String.Manipulation.cs
- Kaynak:
- String.Manipulation.cs
Belirtilen sınırlandırma karakterlerine ve seçeneklerine göre bir dizeyi alt dizelere böler.
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()
Parametreler
- separator
- Char[]
Bu dizedeki alt dizeleri sınırlandıran bir karakter dizisi, sınırlayıcı içermeyen boş bir dizi veya null
.
- options
- StringSplitOptions
Alt dizelerin kırpılıp kırpılmayacağını ve boş alt dizelerin eklenip eklenmeyeceğini belirten sabit listesi değerlerinin bit düzeyinde birleşimi.
Döndürülenler
Öğeleri bu dizedeki içinde bir veya daha fazla karakterle separator
sınırlandırılmış alt dizeleri içeren bir dizi. Daha fazla bilgi için Açıklamalar bölümüne bakın.
- Öznitelikler
Özel durumlar
options
değerlerden biri StringSplitOptions değildir.
Örnekler
Aşağıdaki örnek, yöntemi tarafından oluşturulan alt dizeleri dahil etmek veya hariç tutmak için numaralandırmayı Split kullanırStringSplitOptions.
// 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.
// Example 1: Split a string delimited by characters
Console.WriteLine("1) Split a string delimited by characters:\n");
string s1 = ",ONE,, TWO,, , THREE,,";
char[] charSeparators = new char[] { ',' };
string[] result;
Console.WriteLine($"The original string is: \"{s1}\".");
Console.WriteLine($"The delimiter character is: '{charSeparators[0]}'.\n");
// Split the string and return all elements
Console.WriteLine("1a) Return all elements:");
result = s1.Split(charSeparators, StringSplitOptions.None);
Show(result);
// Split the string and return all elements with whitespace trimmed
Console.WriteLine("1b) Return all elements with whitespace trimmed:");
result = s1.Split(charSeparators, StringSplitOptions.TrimEntries);
Show(result);
// Split the string and return all non-empty elements
Console.WriteLine("1c) Return all non-empty elements:");
result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// Split the string and return all non-whitespace elements with whitespace trimmed
Console.WriteLine("1d) Return all non-whitespace elements with whitespace trimmed:");
result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
Show(result);
// Split the string into only two elements, keeping the remainder in the last match
Console.WriteLine("1e) Split into only two elements:");
result = s1.Split(charSeparators, 2, StringSplitOptions.None);
Show(result);
// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("1f) Split into only two elements with whitespace trimmed:");
result = s1.Split(charSeparators, 2, StringSplitOptions.TrimEntries);
Show(result);
// Split the string into only two non-empty elements, keeping the remainder in the last match
Console.WriteLine("1g) Split into only two non-empty elements:");
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("1h) Split into only two non-whitespace elements with whitespace trimmed:");
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
Show(result);
// Example 2: Split a string delimited by another string
Console.WriteLine("2) Split a string delimited by another string:\n");
string s2 = "[stop]" +
"ONE[stop] [stop]" +
"TWO [stop][stop] [stop]" +
"THREE[stop][stop] ";
string[] stringSeparators = new string[] { "[stop]" };
Console.WriteLine($"The original string is: \"{s2}\".");
Console.WriteLine($"The delimiter string is: \"{stringSeparators[0]}\".\n");
// Split the string and return all elements
Console.WriteLine("2a) Return all elements:");
result = s2.Split(stringSeparators, StringSplitOptions.None);
Show(result);
// Split the string and return all elements with whitespace trimmed
Console.WriteLine("2b) Return all elements with whitespace trimmed:");
result = s2.Split(stringSeparators, StringSplitOptions.TrimEntries);
Show(result);
// Split the string and return all non-empty elements
Console.WriteLine("2c) Return all non-empty elements:");
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// Split the string and return all non-whitespace elements with whitespace trimmed
Console.WriteLine("2d) Return all non-whitespace elements with whitespace trimmed:");
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
Show(result);
// Split the string into only two elements, keeping the remainder in the last match
Console.WriteLine("2e) Split into only two elements:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.None);
Show(result);
// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("2f) Split into only two elements with whitespace trimmed:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.TrimEntries);
Show(result);
// Split the string into only two non-empty elements, keeping the remainder in the last match
Console.WriteLine("2g) Split into only two non-empty elements:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries);
Show(result);
// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("2h) Split into only two non-whitespace elements with whitespace trimmed:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
Show(result);
// Display the array of separated strings using a local function
void Show(string[] entries)
{
Console.WriteLine($"The return value contains these {entries.Length} elements:");
foreach (string entry in entries)
{
Console.Write($"<{entry}>");
}
Console.Write("\n\n");
}
/*
This example produces the following results:
1) Split a string delimited by characters:
The original string is: ",ONE,, TWO,, , THREE,,".
The delimiter character is: ','.
1a) Return all elements:
The return value contains these 9 elements:
<><ONE><>< TWO><>< >< THREE><><>
1b) Return all elements with whitespace trimmed:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>
1c) Return all non-empty elements:
The return value contains these 4 elements:
<ONE>< TWO>< >< THREE>
1d) Return all non-whitespace elements with whitespace trimmed:
The return value contains these 3 elements:
<ONE><TWO><THREE>
1e) Split into only two elements:
The return value contains these 2 elements:
<><ONE,, TWO,, , THREE,,>
1f) Split into only two elements with whitespace trimmed:
The return value contains these 2 elements:
<><ONE,, TWO,, , THREE,,>
1g) Split into only two non-empty elements:
The return value contains these 2 elements:
<ONE>< TWO,, , THREE,,>
1h) Split into only two non-whitespace elements with whitespace trimmed:
The return value contains these 2 elements:
<ONE><TWO,, , THREE,,>
2) Split a string delimited by another string:
The original string is: "[stop]ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] ".
The delimiter string is: "[stop]".
2a) Return all elements:
The return value contains these 9 elements:
<><ONE>< ><TWO ><>< ><THREE><>< >
2b) Return all elements with whitespace trimmed:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>
2c) Return all non-empty elements:
The return value contains these 6 elements:
<ONE>< ><TWO >< ><THREE>< >
2d) Return all non-whitespace elements with whitespace trimmed:
The return value contains these 3 elements:
<ONE><TWO><THREE>
2e) Split into only two elements:
The return value contains these 2 elements:
<><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] >
2f) Split into only two elements with whitespace trimmed:
The return value contains these 2 elements:
<><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop]>
2g) Split into only two non-empty elements:
The return value contains these 2 elements:
<ONE>< [stop]TWO [stop][stop] [stop]THREE[stop][stop] >
2h) Split into only two non-whitespace elements with whitespace trimmed:
The return value contains these 2 elements:
<ONE><TWO [stop][stop] [stop]THREE[stop][stop]>
*/
// This example demonstrates the String.Split() methods that use
// the StringSplitOptions enumeration.
// Display the array of separated strings using a local function
let show (entries: string[]) =
printfn $"The return value contains these {entries.Length} elements:"
for entry in entries do
printf $"<{entry}>"
printf "\n\n"
// Example 1: Split a string delimited by characters
printfn "1) Split a string delimited by characters:\n"
let s1 = ",ONE,, TWO,, , THREE,,"
let charSeparators = [| ',' |]
printfn $"The original string is: \"{s1}\"."
printfn $"The delimiter character is: '{charSeparators[0]}'.\n"
// Split the string and return all elements
printfn "1a) Return all elements:"
let result = s1.Split(charSeparators, StringSplitOptions.None)
show result
// Split the string and return all elements with whitespace trimmed
printfn "1b) Return all elements with whitespace trimmed:"
let result = s1.Split(charSeparators, StringSplitOptions.TrimEntries)
show result
// Split the string and return all non-empty elements
printfn "1c) Return all non-empty elements:"
let result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries)
show result
// Split the string and return all non-whitespace elements with whitespace trimmed
printfn "1d) Return all non-whitespace elements with whitespace trimmed:"
let result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)
show result
// Split the string into only two elements, keeping the remainder in the last match
printfn "1e) Split into only two elements:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.None)
show result
// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
printfn "1f) Split into only two elements with whitespace trimmed:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.TrimEntries)
show result
// Split the string into only two non-empty elements, keeping the remainder in the last match
printfn "1g) Split into only two non-empty elements:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
show result
// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
printfn "1h) Split into only two non-whitespace elements with whitespace trimmed:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)
show result
// Example 2: Split a string delimited by another string
printfn "2) Split a string delimited by another string:\n"
let s2 = "[stop]" +
"ONE[stop] [stop]" +
"TWO [stop][stop] [stop]" +
"THREE[stop][stop] "
let stringSeparators = [| "[stop]" |]
printfn $"The original string is: \"{s2}\"."
printfn $"The delimiter string is: \"{stringSeparators[0]}\".\n"
// Split the string and return all elements
printfn "2a) Return all elements:"
let result = s2.Split(stringSeparators, StringSplitOptions.None)
show result
// Split the string and return all elements with whitespace trimmed
printfn "2b) Return all elements with whitespace trimmed:"
let result = s2.Split(stringSeparators, StringSplitOptions.TrimEntries)
show result
// Split the string and return all non-empty elements
printfn "2c) Return all non-empty elements:"
let result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)
show result
// Split the string and return all non-whitespace elements with whitespace trimmed
printfn "2d) Return all non-whitespace elements with whitespace trimmed:"
let result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)
show result
// Split the string into only two elements, keeping the remainder in the last match
printfn "2e) Split into only two elements:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.None)
show result
// Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
printfn "2f) Split into only two elements with whitespace trimmed:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.TrimEntries)
show result
// Split the string into only two non-empty elements, keeping the remainder in the last match
printfn "2g) Split into only two non-empty elements:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
show result
// Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
printfn "2h) Split into only two non-whitespace elements with whitespace trimmed:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries ||| StringSplitOptions.TrimEntries)
show result
(*
This example produces the following results:
1) Split a string delimited by characters:
The original string is: ",ONE,, TWO,, , THREE,,".
The delimiter character is: ','.
1a) Return all elements:
The return value contains these 9 elements:
<><ONE><>< TWO><>< >< THREE><><>
1b) Return all elements with whitespace trimmed:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>
1c) Return all non-empty elements:
The return value contains these 4 elements:
<ONE>< TWO>< >< THREE>
1d) Return all non-whitespace elements with whitespace trimmed:
The return value contains these 3 elements:
<ONE><TWO><THREE>
1e) Split into only two elements:
The return value contains these 2 elements:
<><ONE,, TWO,, , THREE,,>
1f) Split into only two elements with whitespace trimmed:
The return value contains these 2 elements:
<><ONE,, TWO,, , THREE,,>
1g) Split into only two non-empty elements:
The return value contains these 2 elements:
<ONE>< TWO,, , THREE,,>
1h) Split into only two non-whitespace elements with whitespace trimmed:
The return value contains these 2 elements:
<ONE><TWO,, , THREE,,>
2) Split a string delimited by another string:
The original string is: "[stop]ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] ".
The delimiter string is: "[stop]".
2a) Return all elements:
The return value contains these 9 elements:
<><ONE>< ><TWO ><>< ><THREE><>< >
2b) Return all elements with whitespace trimmed:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>
2c) Return all non-empty elements:
The return value contains these 6 elements:
<ONE>< ><TWO >< ><THREE>< >
2d) Return all non-whitespace elements with whitespace trimmed:
The return value contains these 3 elements:
<ONE><TWO><THREE>
2e) Split into only two elements:
The return value contains these 2 elements:
<><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] >
2f) Split into only two elements with whitespace trimmed:
The return value contains these 2 elements:
<><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop]>
2g) Split into only two non-empty elements:
The return value contains these 2 elements:
<ONE>< [stop]TWO [stop][stop] [stop]THREE[stop][stop] >
2h) Split into only two non-whitespace elements with whitespace trimmed:
The return value contains these 2 elements:
<ONE><TWO [stop][stop] [stop]THREE[stop][stop]>
*)
Public Shared Sub StringSplitOptionsExamples()
' This example demonstrates the String.Split() methods that use
' the StringSplitOptions enumeration.
' Example 1: Split a string delimited by characters
Console.WriteLine("1) Split a string delimited by characters:" & vbCrLf)
Dim s1 As String = ",ONE,, TWO,, , THREE,,"
Dim charSeparators() As Char = {","c}
Dim result() As String
Console.WriteLine("The original string is: ""{0}"".", s1)
Console.WriteLine("The delimiter character is: '{0}'." & vbCrLf, charSeparators(0))
' Split the string and return all elements
Console.WriteLine("1a) Return all elements:")
result = s1.Split(charSeparators, StringSplitOptions.None)
Show(result)
' Split the string and return all elements with whitespace trimmed
Console.WriteLine("1b) Return all elements with whitespace trimmed:")
result = s1.Split(charSeparators, StringSplitOptions.TrimEntries)
Show(result)
' Split the string and return all non-empty elements
Console.WriteLine("1c) Return all non-empty elements:")
result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries)
Show(result)
' Split the string and return all non-whitespace elements with whitespace trimmed
Console.WriteLine("1d) Return all non-whitespace elements with whitespace trimmed:")
result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries)
Show(result)
' Split the string into only two elements, keeping the remainder in the last match
Console.WriteLine("1e) Split into only two elements:")
result = s1.Split(charSeparators, 2, StringSplitOptions.None)
Show(result)
' Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("1f) Split into only two elements with whitespace trimmed:")
result = s1.Split(charSeparators, 2, StringSplitOptions.TrimEntries)
Show(result)
' Split the string into only two non-empty elements, keeping the remainder in the last match
Console.WriteLine("1g) Split into only two non-empty elements:")
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
Show(result)
' Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("1h) Split into only two non-whitespace elements with whitespace trimmed:")
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries)
Show(result)
' Example 2: Split a string delimited by another string
Console.WriteLine("2) Split a string delimited by another string:" & vbCrLf)
Dim s2 As String = "[stop]" +
"ONE[stop] [stop]" +
"TWO [stop][stop] [stop]" +
"THREE[stop][stop] "
Dim stringSeparators() As String = {"[stop]"}
Console.WriteLine("The original string is: ""{0}"".", s2)
Console.WriteLine("The delimiter string is: ""{0}""." & vbCrLf, stringSeparators(0))
' Split the string and return all elements
Console.WriteLine("2a) Return all elements:")
result = s2.Split(stringSeparators, StringSplitOptions.None)
Show(result)
' Split the string and return all elements with whitespace trimmed
Console.WriteLine("2b) Return all elements with whitespace trimmed:")
result = s2.Split(stringSeparators, StringSplitOptions.TrimEntries)
Show(result)
' Split the string and return all non-empty elements
Console.WriteLine("2c) Return all non-empty elements:")
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)
Show(result)
' Split the string and return all non-whitespace elements with whitespace trimmed
Console.WriteLine("2d) Return all non-whitespace elements with whitespace trimmed:")
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries)
Show(result)
' Split the string into only two elements, keeping the remainder in the last match
Console.WriteLine("2e) Split into only two elements:")
result = s2.Split(stringSeparators, 2, StringSplitOptions.None)
Show(result)
' Split the string into only two elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("2f) Split into only two elements with whitespace trimmed:")
result = s2.Split(stringSeparators, 2, StringSplitOptions.TrimEntries)
Show(result)
' Split the string into only two non-empty elements, keeping the remainder in the last match
Console.WriteLine("2g) Split into only two non-empty elements:")
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
Show(result)
' Split the string into only two non-whitespace elements with whitespace trimmed, keeping the remainder in the last match
Console.WriteLine("2h) Split into only two non-whitespace elements with whitespace trimmed:")
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries)
Show(result)
End Sub
' Display the array of separated strings.
Public Shared Sub Show(ByVal entries() As String)
Console.WriteLine("The return value contains these {0} elements:", entries.Length)
Dim entry As String
For Each entry In entries
Console.Write("<{0}>", entry)
Next entry
Console.Write(vbCrLf & vbCrLf)
End Sub
'This example produces the following results:
'
' 1) Split a string delimited by characters:
'
' The original string is: ",ONE,, TWO,, , THREE,,".
' The delimiter character is: ','.
'
' 1a) Return all elements:
' The return value contains these 9 elements:
' <><ONE><>< TWO><>< >< THREE><><>
'
' 1b) Return all elements with whitespace trimmed:
' The return value contains these 9 elements:
' <><ONE><><TWO><><><THREE><><>
'
' 1c) Return all non-empty elements:
' The return value contains these 4 elements:
' <ONE>< TWO>< >< THREE>
'
' 1d) Return all non-whitespace elements with whitespace trimmed:
' The return value contains these 3 elements:
' <ONE><TWO><THREE>
'
' 1e) Split into only two elements:
' The return value contains these 2 elements:
' <><ONE,, TWO,, , THREE,,>
'
' 1f) Split into only two elements with whitespace trimmed:
' The return value contains these 2 elements:
' <><ONE,, TWO,, , THREE,,>
'
' 1g) Split into only two non-empty elements:
' The return value contains these 2 elements:
' <ONE>< TWO,, , THREE,,>
'
' 1h) Split into only two non-whitespace elements with whitespace trimmed:
' The return value contains these 2 elements:
' <ONE><TWO,, , THREE,,>
'
' 2) Split a string delimited by another string:
'
' The original string is: "[stop]ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] ".
' The delimiter string is: "[stop]".
'
' 2a) Return all elements:
' The return value contains these 9 elements:
' <><ONE>< ><TWO ><>< ><THREE><>< >
'
' 2b) Return all elements with whitespace trimmed:
' The return value contains these 9 elements:
' <><ONE><><TWO><><><THREE><><>
'
' 2c) Return all non-empty elements:
' The return value contains these 6 elements:
' <ONE>< ><TWO >< ><THREE>< >
'
' 2d) Return all non-whitespace elements with whitespace trimmed:
' The return value contains these 3 elements:
' <ONE><TWO><THREE>
'
' 2e) Split into only two elements:
' The return value contains these 2 elements:
' <><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop] >
'
' 2f) Split into only two elements with whitespace trimmed:
' The return value contains these 2 elements:
' <><ONE[stop] [stop]TWO [stop][stop] [stop]THREE[stop][stop]>
'
' 2g) Split into only two non-empty elements:
' The return value contains these 2 elements:
' <ONE>< [stop]TWO [stop][stop] [stop]THREE[stop][stop] >
'
' 2h) Split into only two non-whitespace elements with whitespace trimmed:
' The return value contains these 2 elements:
' <ONE><TWO [stop][stop] [stop]THREE[stop][stop]>
'
Açıklamalar
Sınırlayıcı karakterler (dizideki separator
karakterler) döndürülen dizinin öğelerine dahil değildir. Örneğin, separator
dizi "-" karakterini içeriyorsa ve geçerli dize örneğinin değeri "aa-bb-cc" ise, yöntem üç öğe içeren bir dizi döndürür: "aa", "bb", ve "cc".
Bu örnek içindeki separator
karakterlerden herhangi birini içermiyorsa, döndürülen dizi bu örneği içeren tek bir öğeden oluşur.
options
parametresi ise RemoveEmptyEntries ve bu örneğin uzunluğu sıfırsa, yöntem boş bir dizi döndürür.
öğesinin separator
her öğesi, tek bir karakterden oluşan ayrı bir sınırlayıcı tanımlar. options
Bağımsız değişken ise Noneve iki sınırlayıcı bitişikse veya bu örneğin başında veya sonunda bir sınırlayıcı bulunursa, karşılık gelen dizi öğesi öğesini içerirString.Empty. Örneğin, separator
ve olmak üzere iki öğe içeriyorsa, '_'
'-'
dize örneğinin değeri "-_aa-_" ve bağımsız değişkeninin options
değeri ise None, yöntemi aşağıdaki beş öğeyi içeren bir dize dizisi döndürür:
String.Empty, 0 dizinindeki "-" karakterinden önce gelen boş dizeyi temsil eder.
String.Empty, dizin 0'daki "-" karakteri ile dizin 1'deki "_" karakteri arasındaki boş dizeyi temsil eder.
"aa".
String.Empty, dizin 4'teki "-" karakterini izleyen boş dizeyi temsil eder.
String.Empty, dizin 5'teki "_" karakterini izleyen boş dizeyi temsil eder.
Ayırıcı dizi
separator
Parametre karakter null
içeriyorsa veya karakter içermiyorsa, boşluk karakterlerinin sınırlayıcı olduğu varsayılır. Boşluk karakterleri Unicode standardı tarafından tanımlanır ve Char.IsWhiteSpace yöntem, bu karaktere geçirilirse döndürür true
.
parametresini char[] separator
geçirmek null
için, çağrısının null
gibi Split(String[], StringSplitOptions)diğer bazı aşırı yüklemelerden belirsiz olmasını sağlamak için türünü belirtmeniz gerekir. Aşağıdaki örnekte, bu aşırı yükü belirsiz şekilde tanımlamanın çeşitli yolları gösterilmektedir.
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)
Karşılaştırma ayrıntıları
Split yöntemi, bu dizedeki parametredeki bir veya daha fazla karakterle separator
sınırlandırılmış alt dizeleri ayıklar ve bu alt dizeleri bir dizinin öğeleri olarak döndürür.
yöntemi, Split büyük/küçük harfe duyarlı sıralı sıralama kurallarını kullanarak karşılaştırmalar yaparak sınırlayıcıları arar. Sözcük, dize ve sıralı sıralamalar hakkında daha fazla bilgi için numaralandırmaya System.Globalization.CompareOptions bakın.
Performansla ilgili önemli noktalar
Yöntemler, Split döndürülen dizi nesnesi için bellek ve her dizi öğesi için bir String nesne ayırır. Uygulamanız en iyi performansı gerektiriyorsa veya uygulamanızda bellek ayırmayı yönetmek kritik önem taşıyorsa, dize içindeki bir alt dizeyi bulmak için veya IndexOfAny yöntemini ve isteğe bağlı olarak Compare yöntemini kullanmayı IndexOf göz önünde bulundurun.
Bir dizeyi ayırıcı karakterde bölüyorsanız, dizede IndexOf ayırıcı karakteri bulmak için veya IndexOfAny yöntemini kullanın. Bir dizeyi ayırıcı dizeye bölüyorsanız, ayırıcı dizenin IndexOf ilk karakterini bulmak için veya IndexOfAny yöntemini kullanın. Ardından, Compare ilk karakterden sonraki karakterlerin ayırıcı dizenin kalan karakterlerine eşit olup olmadığını belirlemek için yöntemini kullanın.
Ayrıca, dizeleri birden çok Split yöntem çağrısında bölmek için aynı karakter kümesi kullanılıyorsa, tek bir dizi oluşturmayı ve her yöntem çağrısında buna başvurmayı göz önünde bulundurun. Bu, her yöntem çağrısının ek yükünü önemli ölçüde azaltır.
Arayanlara Notlar
.NET Framework 3.5 ve önceki sürümlerde, yöntem karakter içermeyen veya karakter içermeyen bir null
separator
yönteme geçirilirseSplit(Char[]), yöntem dizeyi bölmek için, yöntemin dizeyi kırpmak için kullandığından Trim(Char[]) biraz farklı bir boşluk karakterleri kümesi kullanır. .NET Framework 4'den başlayarak, her iki yöntem de aynı Unicode boşluk karakterleri kümesini kullanır.
Şunlara uygulanır
Geri Bildirim
https://aka.ms/ContentUserFeedback.
Çok yakında: 2024 boyunca, içerik için geri bildirim mekanizması olarak GitHub Sorunları’nı kullanımdan kaldıracak ve yeni bir geri bildirim sistemiyle değiştireceğiz. Daha fazla bilgi için bkz.Gönderin ve geri bildirimi görüntüleyin