String.Split 메서드
정의
중요
일부 정보는 릴리스되기 전에 상당 부분 수정될 수 있는 시험판 제품과 관련이 있습니다. Microsoft는 여기에 제공된 정보에 대해 어떠한 명시적이거나 묵시적인 보증도 하지 않습니다.
지정된 문자열 또는 유니코드 문자 배열의 요소로 구분된 이 인스턴스의 부분 문자열이 포함된 문자열 배열을 반환합니다.
오버로드
Split(String, Int32, StringSplitOptions) |
지정된 구분 문자열 및 옵션(필요에 따라)에 따라 문자열을 최대 개수의 부분 문자열로 분할합니다. |
Split(Char[], Int32, StringSplitOptions) |
지정된 구분 문자 및 옵션(필요에 따라)에 따라 문자열을 최대 개수의 부분 문자열로 분할합니다. |
Split(Char, Int32, StringSplitOptions) |
지정된 구분 문자 및 옵션(필요에 따라)에 따라 문자열을 최대 개수의 부분 문자열로 분할합니다. 제공된 문자 구분 기호에 따라 문자열을 최대 개수의 부분 문자열로 분할하고 필요에 따라 결과에서 빈 부분 문자열을 생략합니다. |
Split(String[], StringSplitOptions) |
지정된 구분 문자열 및 옵션(필요에 따라)에 따라 문자열을 부분 문자열로 분할합니다. |
Split(String, StringSplitOptions) |
문자열을 제공된 문자열 구분 기호에 기초하는 부분 문자열로 분할합니다. |
Split(Char[]) |
지정된 구분 문자에 따라 문자열을 부분 문자열로 분할합니다. |
Split(Char[], Int32) |
지정된 구분 문자에 따라 문자열을 최대 개수의 부분 문자열로 분할합니다. |
Split(Char, StringSplitOptions) |
지정된 구분 문자 및 옵션(필요에 따라)에 따라 문자열을 부분 문자열로 분할합니다. |
Split(ReadOnlySpan<Char>) | |
Split(String[], Int32, StringSplitOptions) |
지정된 구분 문자열 및 옵션(필요에 따라)에 따라 문자열을 최대 개수의 부분 문자열로 분할합니다. |
Split(Char[], StringSplitOptions) |
지정된 구분 문자 및 옵션에 따라 문자열을 부분 문자열로 분할합니다. |
설명
Split 는 구분된 문자열을 부분 문자열로 분리하는 데 사용됩니다. 문자 배열 또는 문자열 배열을 사용하여 0개 이상의 구분 문자 또는 문자열을 지정할 수 있습니다. 구분 문자를 지정하지 않으면 문자열이 공백 문자로 분할됩니다.
메서드의 Split 오버로드를 사용하면 메서드(Split(Char[], Int32)메서드)에서 반환하는 부분 문자열의 수를 제한하고, 빈 문자열을 포함할지, 아니면 결과(및 메서드)에 부분 문자열을 트리밍할지 또는 둘 다 수행할지(Split(Char[], StringSplitOptions)Split(Char[], Int32, StringSplitOptions) 및 Split(String[], StringSplitOptions)Split(String[], Int32, StringSplitOptions) 메서드)를 지정할 수 있습니다.
팁
Split 메서드가 항상 구분된 문자열을 부분 문자열로 분리하는 가장 좋은 방법은 아닙니다. 구분된 문자열의 모든 부분 문자열을 추출하지 않으려는 경우 또는 구분 기호 문자 집합 대신 패턴에 따라 문자열을 구문 분석하려는 경우 정규식을 사용하거나 문자의 인덱스를 반환하는 검색 메서드 중 하나를 메서드와 Substring 결합하는 것이 좋습니다. 자세한 내용은 문자열에서 부분 문자열 추출을 참조하세요.
예제
다음 예제는 String.Split()
의 세 가지 오버로드를 보여 줍니다. 첫 번째 예제에서는 오버로드를 Split(Char[]) 호출하고 단일 구분 기호를 전달합니다.
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.
여기에서 볼 수 있듯이 마침표 문자(.
)가 두 부분 문자열에 포함됩니다. 마침표 문자를 제외하려는 경우 마침표 문자를 추가 구분 문자로 추가할 수 있습니다. 다음 예제는 이 작업을 수행하는 방법을 보여 줍니다.
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:
부분 문자열에서 마침표가 사라졌지만 이제는 두 개의 빈 부분 문자열이 추가로 포함되었습니다. 이러한 빈 부분 문자열은 단어와 단어 뒤의 마침표 사이의 부분 문자열을 나타냅니다. 결과 배열에서 빈 부분 문자열을 생략하려면 Split(Char[], StringSplitOptions) 오버로드를 호출하고 options
매개 변수의 StringSplitOptions.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
의 String.Split()
개별 오버로드에 대한 섹션에는 추가 예제가 포함되어 있습니다.
Split(String, Int32, StringSplitOptions)
- Source:
- String.Manipulation.cs
- Source:
- String.Manipulation.cs
- Source:
- String.Manipulation.cs
지정된 구분 문자열 및 옵션(필요에 따라)에 따라 문자열을 최대 개수의 부분 문자열로 분할합니다.
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()
매개 변수
- separator
- String
이 인스턴스에서 부분 문자열을 구분하는 문자열입니다.
- count
- Int32
배열에 필요한 최대 요소 수입니다.
- options
- StringSplitOptions
부분 문자열을 자르고 빈 부분 문자열을 포함할지를 지정하는 열거형 값의 비트 조합입니다.
반환
separator
로 구분되는 이 인스턴스의 부분 문자열이 최대 count
개 포함된 배열입니다.
설명
문자열이 이미 1번 분할 count
되었지만 문자열의 끝에 도달하지 않은 경우 반환된 배열의 마지막 문자열에는 이 instance 나머지 후행 부분 문자열이 그대로 포함됩니다.
적용 대상
Split(Char[], Int32, StringSplitOptions)
- Source:
- String.Manipulation.cs
- Source:
- String.Manipulation.cs
- Source:
- String.Manipulation.cs
지정된 구분 문자 및 옵션(필요에 따라)에 따라 문자열을 최대 개수의 부분 문자열로 분할합니다.
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()
매개 변수
- separator
- Char[]
이 문자열의 부분 문자열을 구분하는 문자 배열, 구분 기호를 포함하지 않는 빈 배열 또는 null
입니다.
- count
- Int32
반환할 부분 문자열의 최대 수입니다.
- options
- StringSplitOptions
부분 문자열을 자르고 빈 부분 문자열을 포함할지를 지정하는 열거형 값의 비트 조합입니다.
반환
separator
에 있는 하나 이상의 문자로 구분되는 이 문자열의 부분 문자열이 포함된 배열입니다. 자세한 내용은 설명 섹션을 참조하세요.
- 특성
예외
count
가 음수입니다.
options
가 StringSplitOptions 값 중 하나가 아닙니다.
예제
다음 예제에서는 열거형을 사용하여 StringSplitOptions 메서드에서 생성된 Split 부분 문자열을 포함하거나 제외합니다.
// This example demonstrates the String.Split(Char[], Boolean) and
// String.Split(Char[], Int32, Boolean) methods
using namespace System;
void Show( array<String^>^entries )
{
Console::WriteLine( "The return value contains these {0} elements:", entries->Length );
System::Collections::IEnumerator^ myEnum = entries->GetEnumerator();
while ( myEnum->MoveNext() )
{
String^ entry = safe_cast<String^>(myEnum->Current);
Console::Write( "<{0}>", entry );
}
Console::Write( "{0}{0}", Environment::NewLine );
}
int main()
{
String^ s = ",one,,,two,,,,,three,,";
array<Char>^sep = gcnew array<Char>{
','
};
array<String^>^result;
//
Console::WriteLine( "The original string is \"{0}\".", s );
Console::WriteLine( "The separation character is '{0}'.", sep[ 0 ] );
Console::WriteLine();
//
Console::WriteLine( "Split the string and return all elements:" );
result = s->Split( sep, StringSplitOptions::None );
Show( result );
//
Console::WriteLine( "Split the string and return all non-empty elements:" );
result = s->Split( sep, StringSplitOptions::RemoveEmptyEntries );
Show( result );
//
Console::WriteLine( "Split the string and return 2 elements:" );
result = s->Split( sep, 2, StringSplitOptions::None );
Show( result );
//
Console::WriteLine( "Split the string and return 2 non-empty elements:" );
result = s->Split( sep, 2, StringSplitOptions::RemoveEmptyEntries );
Show( result );
}
/*
This example produces the following results:
The original string is ",one,,,two,,,,,three,,".
The separation character is ','.
Split the string and return all elements:
The return value contains these 12 elements:
<><one><><><two><><><><><three><><>
Split the string and return all non-empty elements:
The return value contains these 3 elements:
<one><two><three>
Split the string and return 2 elements:
The return value contains these 2 elements:
<><one,,,two,,,,,three,,>
Split the string and return 2 non-empty elements:
The return value contains these 2 elements:
<one><,,two,,,,,three,,>
*/
// This example demonstrates the String.Split() methods that use
// the StringSplitOptions enumeration.
// 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]>
'
설명
구분 기호 문자는 반환된 배열의 요소에 포함되지 않습니다.
이 instance 의 문자를 separator
count
포함하지 않거나 매개 변수가 1인 경우 반환된 배열은 이 instance 포함하는 단일 요소로 구성됩니다.
매개 변수가 separator
이거나 null
문자가 없는 경우 공백 문자는 구분 기호로 간주됩니다. 공백 문자는 유니코드 표준에 의해 정의되고 메서드는 Char.IsWhiteSpace 전달되면 를 반환 true
합니다.
매개 변수에 대해 전달 null
하려면 와 같은 Split(String[], Int32, StringSplitOptions)다른 오버로드에서 호출을 명확히 하기 위해 의 null
형식을 나타내야 char[] separator
합니다. 다음 예제에서는 이 오버로드를 명확하게 식별하는 여러 가지 방법을 보여줍니다.
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
0이거나 매개 변수가 options
이 RemoveEmptyEntries 고 이 instance 길이가 0이면 빈 배열이 반환됩니다.
의 separator
각 요소는 별도의 구분 기호 문자를 정의합니다. 매개 변수가 options
None이고 두 구분 기호가 인접하거나 이 instance 시작 또는 끝에 구분 기호가 있는 경우 해당 배열 요소에 가 포함됩니다Empty.
이 instance 하위 문자열이 여러 count
개 있는 경우 첫 번째 count
빼기 1개 부분 문자열은 반환 값의 첫 번째 count
빼기 1개 요소에 반환되고 이 instance 나머지 문자는 반환 값의 마지막 요소에 반환됩니다.
가 부분 문자열 수보다 크면 count
사용 가능한 부분 문자열이 반환되고 예외가 throw되지 않습니다.
성능 고려 사항
메서드는 Split 반환된 배열 개체에 대한 메모리와 String 각 배열 요소에 대한 개체를 할당합니다. 애플리케이션에 필요한 최적의 성능, 메모리 할당을 관리 하는 것이 중요 애플리케이션 사용을 고려 합니다 IndexOf 또는 IndexOfAny 메서드 및 필요에 따라는 Compare 문자열 내에서 부분 문자열을 찾을 방법입니다.
구분 기호 문자로 문자열을 분할하는 경우 또는 IndexOfAny 메서드를 IndexOf 사용하여 문자열에서 구분 기호 문자를 찾습니다. 구분 기호 문자열에서 문자열을 분할하는 경우 또는 IndexOfAny 메서드를 IndexOf 사용하여 구분 기호 문자열의 첫 번째 문자를 찾습니다. 그런 다음 메서드를 Compare 사용하여 첫 번째 문자 뒤에 있는 문자가 구분 기호 문자열의 나머지 문자와 같은지 여부를 확인합니다.
또한 동일한 문자 집합을 사용하여 여러 Split 메서드 호출에서 문자열을 분할하는 경우 단일 배열을 만들고 각 메서드 호출에서 참조하는 것이 좋습니다. 이렇게 하면 각 메서드 호출의 추가 오버헤드가 크게 줄어듭니다.
호출자 참고
.NET Framework 3.5 이전 버전에서 메서드가 전달되거나 separator
문자가 없는 경우 Split(Char[]) 메서드는 null
약간 다른 공백 문자 집합을 사용하여 메서드가 문자열을 자르는 것과는 다른 Trim(Char[]) 문자열을 분할합니다. .NET Framework 4부터 두 메서드 모두 동일한 유니코드 공백 문자 집합을 사용합니다.
적용 대상
Split(Char, Int32, StringSplitOptions)
- Source:
- String.Manipulation.cs
- Source:
- String.Manipulation.cs
- Source:
- String.Manipulation.cs
지정된 구분 문자 및 옵션(필요에 따라)에 따라 문자열을 최대 개수의 부분 문자열로 분할합니다. 제공된 문자 구분 기호에 따라 문자열을 최대 개수의 부분 문자열로 분할하고 필요에 따라 결과에서 빈 부분 문자열을 생략합니다.
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()
매개 변수
- separator
- Char
이 인스턴스에서 부분 문자열을 구분하는 문자입니다.
- count
- Int32
배열에 필요한 최대 요소 수입니다.
- options
- StringSplitOptions
부분 문자열을 자르고 빈 부분 문자열을 포함할지를 지정하는 열거형 값의 비트 조합입니다.
반환
separator
로 구분되는 이 인스턴스의 부분 문자열이 최대 count
개 포함된 배열입니다.
설명
문자열이 이미 1번 분할 count
되었지만 문자열의 끝에 도달하지 않은 경우 반환된 배열의 마지막 문자열에는 이 instance 나머지 후행 부분 문자열이 그대로 포함됩니다.
적용 대상
Split(String[], StringSplitOptions)
- Source:
- String.Manipulation.cs
- Source:
- String.Manipulation.cs
- Source:
- String.Manipulation.cs
지정된 구분 문자열 및 옵션(필요에 따라)에 따라 문자열을 부분 문자열로 분할합니다.
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()
매개 변수
- separator
- String[]
이 문자열의 부분 문자열을 구분하는 문자열 배열, 구분 기호를 포함하지 않는 빈 배열 또는 null
입니다.
- options
- StringSplitOptions
부분 문자열을 자르고 빈 부분 문자열을 포함할지를 지정하는 열거형 값의 비트 조합입니다.
반환
해당 요소에 separator
에 있는 하나 이상의 문자열로 구분되는 이 문자열의 부분 문자열이 포함된 배열입니다. 자세한 내용은 주의 섹션을 참조하세요.
- 특성
예외
options
가 StringSplitOptions 값 중 하나가 아닙니다.
예제
다음 예제에서는 및 와 같은 StringSplitOptions.NoneStringSplitOptions.RemoveEmptyEntries매개 변수를 사용하여 문자열의 메서드 options
를 호출하여 반환되는 배열의 String.Split(String[], StringSplitOptions) 차이를 보여 줍니다.
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'
다음 예제에서는 문장 부호 및 공백 문자를 포함하는 구분 기호 배열을 정의합니다. 값과 함께 이 배열을 StringSplitOptions.RemoveEmptyEntries 메서드에 Split(String[], StringSplitOptions) 전달하면 문자열의 개별 단어로 구성된 배열이 반환됩니다.
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
인수가 로 설정된 StringSplitOptions.RemoveEmptyEntries상태에서 메서드가 options
호출됩니다. 이렇게 하면 반환된 배열에 문장 부호와 공백 문자 간의 빈 부분 문자열 일치를 나타내는 값이 포함 String.Empty 되지 않습니다.
설명
문자열이 알려진 문자열 집합으로 구분된 경우 메서드를 Split 사용하여 문자열을 부분 문자열로 구분할 수 있습니다.
구분 기호 문자열은 반환된 배열의 요소에 포함되지 않습니다. 예를 들어 배열에 separator
문자열 "--"이 포함되어 있고 현재 문자열 instance 값이 "aa--bb--cc"인 경우 메서드는 "aa", "bb" 및 "cc"의 세 가지 요소가 포함된 배열을 반환합니다.
이 instance 의 문자열separator
을 포함하지 않는 경우 반환된 배열은 이 instance 포함하는 단일 요소로 구성됩니다.
매개 변수가 options
이 RemoveEmptyEntries 고 이 instance 길이가 0이면 메서드는 빈 배열을 반환합니다.
의 separator
각 요소는 하나 이상의 문자로 구성된 별도의 구분 기호를 정의합니다. 인수가 options
None이고 두 구분 기호가 인접하거나 이 instance 시작 또는 끝에 구분 기호가 있는 경우 해당 배열 요소에 가 포함됩니다String.Empty. 예를 들어 "-" 및 "_"의 두 요소가 포함된 경우 separator
문자열 instance 값은 "-_aa-_"이고 인수 값 options
은 입니다. 메서드는 None다음 5개의 요소가 있는 문자열 배열을 반환합니다.
String.Empty인덱스 0에서 "-" 부분 문자열 앞에 오는 빈 문자열을 나타냅니다.
String.Empty인덱스 0의 "-" 부분 문자열과 인덱스 1의 "_" 부분 문자열 사이의 빈 문자열을 나타냅니다.
"aa".
String.Empty인덱스 4의 "-" 부분 문자열 뒤에 있는 빈 문자열을 나타냅니다.
String.Empty인덱스 5의 "_" 부분 문자열 뒤에 있는 빈 문자열을 나타냅니다.
구분 기호 배열
의 separator
요소가 여러 문자로 구성된 경우 전체 부분 문자열은 구분 기호로 간주됩니다. 예를 들어 의 요소 separator
중 하나가 "10"인 경우 문자열 "This10is10a10string"을 분할하려고 하면 { "This", "is", "a", "string." }의 네 가지 요소 배열이 반환됩니다.
매개 변수가 separator
이거나 null
비어 있지 않은 문자열이 없는 경우 공백 문자는 구분 기호로 간주됩니다. 공백 문자는 유니코드 표준에 의해 정의되고 메서드는 Char.IsWhiteSpace 전달되면 를 반환 true
합니다.
매개 변수에 대해 전달 null
하려면 와 같은 Split(Char[], StringSplitOptions)다른 오버로드에서 호출을 명확히 하기 위해 의 null
형식을 나타내야 string[] separator
합니다. 다음 예제에서는 이 오버로드를 명확하게 식별하는 여러 가지 방법을 보여줍니다.
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)
비교 세부 정보
메서드는 Split 매개 변수에 있는 하나 이상의 문자열로 구분된 이 문자열의 separator
부분 문자열을 추출하고 해당 부분 문자열을 배열의 요소로 반환합니다.
메서드는 Split 대/소문자를 구분하는 서수 정렬 규칙을 사용하여 비교를 수행하여 구분 기호를 찾습니다. 단어, 문자열 및 서수 정렬에 대한 자세한 내용은 열거형을 System.Globalization.CompareOptions 참조하세요.
메서드는 Split 값 null
이 인 의 separator
요소 또는 빈 문자열("")을 무시합니다.
의 문자열에 separator
공통 Split 문자가 있는 경우 모호한 결과를 방지하기 위해 작업은 instance 값의 처음부터 끝까지 진행되며 instance 구분 기호와 동일한 의 첫 번째 요소 separator
와 일치합니다. instance 부분 문자열이 발생하는 순서가 의 요소 separator
순서보다 우선합니다.
예를 들어 값이 "abcdef"인 instance 고려합니다. 의 separator
첫 번째 요소가 "ef"이고 두 번째 요소가 "bcde"인 경우 분할 작업의 결과는 두 개의 요소 "a"와 "f"를 포함하는 문자열 배열이 됩니다. 이는 instance "bcde"의 부분 문자열이 발견되고 부분 문자열 "f"가 발생하기 전에 의 separator
요소와 일치하기 때문입니다.
그러나 의 separator
첫 번째 요소가 "bcd"이고 두 번째 요소가 "bc"인 경우 분할 작업의 결과는 두 개의 요소 "a"와 "ef"를 포함하는 문자열 배열이 됩니다. 이는 "bcd"가 instance 구분 기호와 일치하는 의 첫 번째 구분 separator
기호이기 때문입니다. 첫 번째 요소가 "bc"이고 두 번째 요소가 "bcd"가 되도록 구분 기호의 순서가 반전된 경우 결과는 "a" 및 "def"라는 두 요소를 포함하는 문자열 배열이 됩니다.
성능 고려 사항
메서드는 Split 반환된 배열 개체에 대한 메모리와 String 각 배열 요소에 대한 개체를 할당합니다. 애플리케이션에 필요한 최적의 성능, 메모리 할당을 관리 하는 것이 중요 애플리케이션 사용을 고려 합니다 IndexOf 또는 IndexOfAny 메서드 및 필요에 따라는 Compare 문자열 내에서 부분 문자열을 찾을 방법입니다.
구분 기호 문자로 문자열을 분할하는 경우 또는 IndexOfAny 메서드를 IndexOf 사용하여 문자열에서 구분 기호 문자를 찾습니다. 구분 기호 문자열에서 문자열을 분할하는 경우 또는 IndexOfAny 메서드를 IndexOf 사용하여 구분 기호 문자열의 첫 번째 문자를 찾습니다. 그런 다음 메서드를 Compare 사용하여 첫 번째 문자 뒤에 있는 문자가 구분 기호 문자열의 나머지 문자와 같은지 여부를 확인합니다.
또한 동일한 문자 집합을 사용하여 여러 Split 메서드 호출에서 문자열을 분할하는 경우 단일 배열을 만들고 각 메서드 호출에서 참조하는 것이 좋습니다. 이렇게 하면 각 메서드 호출의 추가 오버헤드가 크게 줄어듭니다.
호출자 참고
.NET Framework 3.5 이전 버전에서 메서드가 전달되거나 separator
문자가 없는 경우 Split(Char[]) 메서드는 null
약간 다른 공백 문자 집합을 사용하여 메서드가 문자열을 자르는 것과는 다른 Trim(Char[]) 문자열을 분할합니다. .NET Framework 4부터 두 메서드 모두 동일한 유니코드 공백 문자 집합을 사용합니다.
적용 대상
Split(String, StringSplitOptions)
- Source:
- String.Manipulation.cs
- Source:
- String.Manipulation.cs
- Source:
- String.Manipulation.cs
문자열을 제공된 문자열 구분 기호에 기초하는 부분 문자열로 분할합니다.
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()
매개 변수
- separator
- String
이 문자열에서 부분 문자열을 구분하는 문자열입니다.
- options
- StringSplitOptions
부분 문자열을 자르고 빈 부분 문자열을 포함할지를 지정하는 열거형 값의 비트 조합입니다.
반환
요소에 separator
로 구분되는 이 인스턴스의 부분 문자열이 포함된 배열입니다.
적용 대상
Split(Char[])
- Source:
- String.Manipulation.cs
- Source:
- String.Manipulation.cs
- Source:
- String.Manipulation.cs
지정된 구분 문자에 따라 문자열을 부분 문자열로 분할합니다.
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()
매개 변수
- separator
- Char[]
구분 문자 배열, 구분 기호를 포함하지 않는 빈 배열 또는 null
입니다.
반환
요소에 separator
에 있는 하나 이상의 문자로 구분되는 이 인스턴스의 부분 문자열이 포함된 배열입니다. 자세한 내용은 주의 섹션을 참조하세요.
예제
다음 예제에서는 공백 문자() 및 탭 문자(
)를 구분 기호로 처리하여 텍스트 블록에서 개별 단어를\t
추출하는 방법을 보여 줍니다. 분할되는 문자열에는 이러한 문자가 모두 포함됩니다.
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
설명
문자열이 알려진 문자 집합으로 구분되는 경우 메서드를 Split(Char[]) 사용하여 문자열을 부분 문자열로 구분할 수 있습니다.
구분 기호 문자는 반환된 배열의 요소에 포함되지 않습니다. 예를 들어 구분 기호 배열에 문자 "-"가 포함되고 현재 문자열 instance 값이 "aa-bb-cc"인 경우 메서드는 "aa", "bb" 및 "cc"의 세 가지 요소가 포함된 배열을 반환합니다.
이 instance 의 separator
문자를 포함하지 않는 경우 반환된 배열은 이 instance 포함하는 단일 요소로 구성됩니다.
의 separator
각 요소는 별도의 구분 기호 문자를 정의합니다. 두 구분 기호가 인접하거나 이 instance 시작 또는 끝에 구분 기호가 있는 경우 반환된 배열의 해당 요소에 가 포함됩니다Empty.
다음 표에서 몇 가지 예를 보여 줍니다.
언어 | 문자열 값 | 구분 기호 | 반환된 배열 |
---|---|---|---|
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# | "바나나" | new Char[] {'.'} | {"Banana"} |
Visual Basic | "바나나" | Char() = {"." c} | {"Banana"} |
C# | "다르브\n스마르바" | new Char[] {} | {"Darb", "Smarba"} |
Visual Basic | "Darb" & vbLf & "Smarba" | Char() = {} | {"Darb", "Smarba"} |
C# | "다르브\n스마르바" | null | {"Darb", "Smarba"} |
Visual Basic | "Darb" & vbLf & "Smarba" | Nothing | {"Darb", "Smarba"} |
구분 기호 배열
구분 기호의 각 요소는 단일 문자로 구성된 별도의 구분 기호를 정의합니다.
인수 null
가 separator
이거나 문자가 없는 경우 메서드는 공백 문자를 구분 기호로 처리합니다. 공백 문자는 유니코드 표준에 의해 정의되며 Char.IsWhiteSpace , 공백 문자가 전달되면 메서드가 를 반환 true
합니다.
String.Split(Char[]) 및 컴파일러 오버로드 확인
이 오버로드 String.Split 에 대한 단일 매개 변수는 문자 배열이지만 다음 예제와 같이 단일 문자로 호출할 수 있습니다.
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.
separator
매개 변수는 특성으로 ParamArrayAttribute 데코레이팅되므로 컴파일러가 단일 문자를 단일 요소 문자 배열로 해석합니다. 매개 변수를 포함하는 separator
다른 String.Split 오버로드의 경우는 그렇지 않습니다. 이러한 오버로드를 인수로 separator
명시적으로 전달해야 합니다.
비교 세부 정보
메서드는 Split(Char[]) 배열에서 하나 이상의 문자 separator
로 구분된 이 문자열의 부분 문자열을 추출하고 해당 부분 문자열을 배열의 요소로 반환합니다.
메서드는 Split(Char[]) 대/소문자를 구분하는 서수 정렬 규칙을 사용하여 비교를 수행하여 구분 기호를 찾습니다. 단어, 문자열 및 서수 정렬에 대한 자세한 내용은 열거형을 System.Globalization.CompareOptions 참조하세요.
성능 고려 사항
메서드는 Split 반환된 배열 개체에 대한 메모리와 String 각 배열 요소에 대한 개체를 할당합니다. 애플리케이션에 필요한 최적의 성능, 메모리 할당을 관리 하는 것이 중요 애플리케이션 사용을 고려 합니다 IndexOf 또는 IndexOfAny 메서드. 메서드를 사용하여 Compare 문자열 내에서 부분 문자열을 찾을 수도 있습니다.
구분 기호 문자에서 문자열을 분할하려면 또는 IndexOfAny 메서드를 IndexOf 사용하여 문자열에서 구분 기호 문자를 찾습니다. 구분 기호 문자열에서 문자열을 분할하려면 또는 IndexOfAny 메서드를 IndexOf 사용하여 구분 기호 문자열의 첫 번째 문자를 찾습니다. 그런 다음 메서드를 Compare 사용하여 첫 번째 문자 뒤에 있는 문자가 구분 기호 문자열의 나머지 문자와 같은지 여부를 확인합니다.
또한 동일한 문자 집합을 사용하여 여러 Split 메서드 호출에서 문자열을 분할하는 경우 단일 배열을 만들고 각 메서드 호출에서 참조하는 것이 좋습니다. 이렇게 하면 각 메서드 호출의 추가 오버헤드가 크게 줄어듭니다.
호출자 참고
.NET Framework 3.5 이전 버전에서 메서드가 전달되거나 separator
문자가 없는 경우 Split(Char[]) 메서드는 null
약간 다른 공백 문자 집합을 사용하여 메서드가 문자열을 자르는 것과는 다른 Trim(Char[]) 문자열을 분할합니다. .NET Framework 4부터 두 메서드 모두 동일한 유니코드 공백 문자 집합을 사용합니다.
추가 정보
- Char
- Concat(Object)
- Insert(Int32, String)
- Join(String, String[])
- Remove(Int32, Int32)
- Replace(Char, Char)
- Substring(Int32)
- Trim(Char[])
적용 대상
Split(Char[], Int32)
- Source:
- String.Manipulation.cs
- Source:
- String.Manipulation.cs
- Source:
- String.Manipulation.cs
지정된 구분 문자에 따라 문자열을 최대 개수의 부분 문자열로 분할합니다.
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()
매개 변수
- separator
- Char[]
이 문자열의 부분 문자열을 구분하는 문자 배열, 구분 기호를 포함하지 않는 빈 배열 또는 null
입니다.
- count
- Int32
반환할 부분 문자열의 최대 수입니다.
반환
해당 요소에 separator
에 있는 하나 이상의 문자로 구분되는 이 인스턴스의 부분 문자열이 포함된 배열입니다. 자세한 내용은 주의 섹션을 참조하세요.
예외
count
가 음수입니다.
예제
다음 예제에서는 에서 반환Split되는 문자열 수를 제한하는 데 사용할 수 있는 방법을 count
보여 줍니다.
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"
설명
구분 기호 문자는 반환된 배열의 요소에 포함되지 않습니다.
이 instance 의 separator
문자를 포함하지 않는 경우 반환된 배열은 이 instance 포함하는 단일 요소로 구성됩니다. 가 0이면 count
빈 배열이 반환됩니다.
매개 변수가 separator
이거나 null
문자가 없는 경우 공백 문자는 구분 기호로 간주됩니다. 공백 문자는 유니코드 표준에 의해 정의되고 메서드는 Char.IsWhiteSpace 전달되면 를 반환 true
합니다.
의 separator
각 요소는 별도의 구분 기호 문자를 정의합니다. 두 구분 기호가 인접하거나 이 instance 시작 또는 끝에 구분 기호가 있는 경우 해당 배열 요소에 가 포함됩니다Empty.
이 instance 하위 문자열 이상이 count
있는 경우 첫 번째 count - 1
부분 문자열은 반환 값의 첫 번째 count - 1
요소에 반환되고 이 instance 나머지 문자는 반환 값의 마지막 요소에 반환됩니다.
가 부분 문자열 수보다 크면 count
사용 가능한 부분 문자열이 반환되고 예외가 throw되지 않습니다.
다음 표에서 몇 가지 예를 보여 줍니다.
언어 | 문자열 값 | 구분 기호 | 반환된 배열 |
---|---|---|---|
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# | "바나나" | new Char[] {'.'} | {"Banana"} |
Visual Basic | "바나나" | Char() = {"." c} | {"Banana"} |
C# | "다르브\n스마르바" | new Char[] {} | {"Darb", "Smarba"} |
Visual Basic | "Darb" & vbLf & "Smarba" | Char() = {} | {"Darb", "Smarba"} |
C# | "다르브\n스마르바" | null | {"Darb", "Smarba"} |
Visual Basic | "Darb" & vbLf & "Smarba" | Nothing | {"Darb", "Smarba"} |
성능 고려 사항
메서드는 Split 반환된 배열 개체에 대한 메모리와 String 각 배열 요소에 대한 개체를 할당합니다. 애플리케이션에 필요한 최적의 성능, 메모리 할당을 관리 하는 것이 중요 애플리케이션 사용을 고려 합니다 IndexOf 또는 IndexOfAny 메서드 및 필요에 따라는 Compare 문자열 내에서 부분 문자열을 찾을 방법입니다.
구분 기호 문자로 문자열을 분할하는 경우 또는 IndexOfAny 메서드를 IndexOf 사용하여 문자열에서 구분 기호 문자를 찾습니다. 구분 기호 문자열에서 문자열을 분할하는 경우 또는 IndexOfAny 메서드를 IndexOf 사용하여 구분 기호 문자열의 첫 번째 문자를 찾습니다. 그런 다음 메서드를 Compare 사용하여 첫 번째 문자 뒤에 있는 문자가 구분 기호 문자열의 나머지 문자와 같은지 여부를 확인합니다.
또한 동일한 문자 집합을 사용하여 여러 Split 메서드 호출에서 문자열을 분할하는 경우 단일 배열을 만들고 각 메서드 호출에서 참조하는 것이 좋습니다. 이렇게 하면 각 메서드 호출의 추가 오버헤드가 크게 줄어듭니다.
호출자 참고
.NET Framework 3.5 이전 버전에서 메서드가 전달되거나 separator
문자가 없는 경우 Split(Char[]) 메서드는 null
약간 다른 공백 문자 집합을 사용하여 메서드가 문자열을 자르는 것과는 다른 Trim(Char[]) 문자열을 분할합니다. .NET Framework 4부터 두 메서드 모두 동일한 유니코드 공백 문자 집합을 사용합니다.
추가 정보
- Char
- Array
- Int32
- Concat(Object)
- Insert(Int32, String)
- Join(String, String[])
- Remove(Int32, Int32)
- Replace(Char, Char)
- Substring(Int32)
- Trim(Char[])
적용 대상
Split(Char, StringSplitOptions)
- Source:
- String.Manipulation.cs
- Source:
- String.Manipulation.cs
- Source:
- String.Manipulation.cs
지정된 구분 문자 및 옵션(필요에 따라)에 따라 문자열을 부분 문자열로 분할합니다.
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()
매개 변수
- separator
- Char
이 문자열에서 부분 문자열을 구분하는 문자입니다.
- options
- StringSplitOptions
부분 문자열을 자르고 빈 부분 문자열을 포함할지를 지정하는 열거형 값의 비트 조합입니다.
반환
요소에 separator
로 구분되는 이 인스턴스의 부분 문자열이 포함된 배열입니다.
적용 대상
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()
매개 변수
- separator
- ReadOnlySpan<Char>
반환
적용 대상
Split(String[], Int32, StringSplitOptions)
- Source:
- String.Manipulation.cs
- Source:
- String.Manipulation.cs
- Source:
- String.Manipulation.cs
지정된 구분 문자열 및 옵션(필요에 따라)에 따라 문자열을 최대 개수의 부분 문자열로 분할합니다.
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()
매개 변수
- separator
- String[]
이 문자열의 부분 문자열을 구분하는 문자열, 구분 기호를 포함하지 않는 빈 배열 또는 null
입니다.
- count
- Int32
반환할 부분 문자열의 최대 수입니다.
- options
- StringSplitOptions
부분 문자열을 자르고 빈 부분 문자열을 포함할지를 지정하는 열거형 값의 비트 조합입니다.
반환
해당 요소에 separator
에 있는 하나 이상의 문자열로 구분되는 이 문자열의 부분 문자열이 포함된 배열입니다. 자세한 내용은 주의 섹션을 참조하세요.
- 특성
예외
count
가 음수입니다.
options
가 StringSplitOptions 값 중 하나가 아닙니다.
예제
다음 예제에서는 열거형을 사용하여 StringSplitOptions 메서드에서 생성된 Split 부분 문자열을 포함하거나 제외합니다.
// This example demonstrates the String.Split(Char[], Boolean) and
// String.Split(Char[], Int32, Boolean) methods
using namespace System;
void Show( array<String^>^entries )
{
Console::WriteLine( "The return value contains these {0} elements:", entries->Length );
System::Collections::IEnumerator^ myEnum = entries->GetEnumerator();
while ( myEnum->MoveNext() )
{
String^ entry = safe_cast<String^>(myEnum->Current);
Console::Write( "<{0}>", entry );
}
Console::Write( "{0}{0}", Environment::NewLine );
}
int main()
{
String^ s = ",one,,,two,,,,,three,,";
array<Char>^sep = gcnew array<Char>{
','
};
array<String^>^result;
//
Console::WriteLine( "The original string is \"{0}\".", s );
Console::WriteLine( "The separation character is '{0}'.", sep[ 0 ] );
Console::WriteLine();
//
Console::WriteLine( "Split the string and return all elements:" );
result = s->Split( sep, StringSplitOptions::None );
Show( result );
//
Console::WriteLine( "Split the string and return all non-empty elements:" );
result = s->Split( sep, StringSplitOptions::RemoveEmptyEntries );
Show( result );
//
Console::WriteLine( "Split the string and return 2 elements:" );
result = s->Split( sep, 2, StringSplitOptions::None );
Show( result );
//
Console::WriteLine( "Split the string and return 2 non-empty elements:" );
result = s->Split( sep, 2, StringSplitOptions::RemoveEmptyEntries );
Show( result );
}
/*
This example produces the following results:
The original string is ",one,,,two,,,,,three,,".
The separation character is ','.
Split the string and return all elements:
The return value contains these 12 elements:
<><one><><><two><><><><><three><><>
Split the string and return all non-empty elements:
The return value contains these 3 elements:
<one><two><three>
Split the string and return 2 elements:
The return value contains these 2 elements:
<><one,,,two,,,,,three,,>
Split the string and return 2 non-empty elements:
The return value contains these 2 elements:
<one><,,two,,,,,three,,>
*/
// This example demonstrates the String.Split() methods that use
// the StringSplitOptions enumeration.
// 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]>
'
설명
구분 기호 문자열은 반환된 배열의 요소에 포함되지 않습니다.
이 instance 에 문자열 separator
count
이 없거나 매개 변수가 1인 경우 반환된 배열은 이 instance 포함하는 단일 요소로 구성됩니다.
매개 변수가 separator
이거나 null
문자가 없는 경우 공백 문자는 구분 기호로 간주됩니다. 공백 문자는 유니코드 표준에 의해 정의되고 메서드는 Char.IsWhiteSpace 전달되면 를 반환 true
합니다.
매개 변수에 대해 전달 null
하려면 와 같은 Split(Char[], Int32, StringSplitOptions)다른 오버로드에서 호출을 명확히 하기 위해 의 null
형식을 나타내야 string[] separator
합니다. 다음 예제에서는 이 오버로드를 명확하게 식별하는 여러 가지 방법을 보여줍니다.
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
0이거나 매개 변수가 options
이 RemoveEmptyEntries 고 이 instance 길이가 0이면 빈 배열이 반환됩니다.
의 separator
각 요소는 하나 이상의 문자로 구성된 별도의 구분 기호를 정의합니다. 매개 변수가 options
None이고 두 구분 기호가 인접하거나 이 instance 시작 또는 끝에 구분 기호가 있는 경우 해당 배열 요소에 가 포함됩니다Empty.
이 instance 하위 문자열이 여러 count
개 있는 경우 첫 번째 count
빼기 1개 부분 문자열은 반환 값의 첫 번째 count
빼기 1개 요소에 반환되고 이 instance 나머지 문자는 반환 값의 마지막 요소에 반환됩니다.
가 부분 문자열 수보다 크면 count
사용 가능한 부분 문자열이 반환되고 예외가 throw되지 않습니다.
구분 기호 배열
의 separator
요소가 여러 문자로 구성된 경우 전체 부분 문자열은 구분 기호로 간주됩니다. 예를 들어 의 요소 separator
중 하나가 "10"이면 문자열 "This10is10a10string"을 분할하려고 합니다. { "This", "is", "a", "string." }의 네 요소 배열을 반환합니다.
비교 세부 정보
메서드는 Split 매개 변수에 있는 하나 이상의 문자열로 구분된 이 문자열의 separator
부분 문자열을 추출하고 해당 부분 문자열을 배열의 요소로 반환합니다.
메서드는 Split 대/소문자를 구분하는 서수 정렬 규칙을 사용하여 비교를 수행하여 구분 기호를 찾습니다. 단어, 문자열 및 서수 정렬에 대한 자세한 내용은 열거형을 System.Globalization.CompareOptions 참조하세요.
메서드는 Split 값 null
이 또는 빈 문자열("")인 의 separator
요소를 무시합니다.
의 문자열 separator
에 공통 Split 문자가 있는 경우 모호한 결과를 방지하기 위해 메서드는 instance 값의 처음부터 끝까지 진행되며 instance 구분 기호와 같은 의 첫 번째 요소 separator
와 일치합니다. instance 부분 문자열이 발생하는 순서가 의 요소 separator
순서보다 우선합니다.
예를 들어 값이 "abcdef"인 instance 고려합니다. 의 separator
첫 번째 요소가 "ef"이고 두 번째 요소가 "bcde"인 경우 분할 작업의 결과는 "a" 및 "f"입니다. 이는 instance "bcde"의 부분 문자열이 발견되고 부분 문자열 "f"가 발생하기 전에 의 separator
요소와 일치하기 때문입니다.
그러나 의 separator
첫 번째 요소가 "bcd"이고 두 번째 요소가 "bc"인 경우 분할 작업의 결과는 "a" 및 "ef"입니다. 이는 "bcd"가 instance 구분 기호와 일치하는 의 separator
첫 번째 구분 기호이기 때문입니다. 구분 기호의 순서가 반전되어 첫 번째 요소가 "bc"이고 두 번째 요소가 "bcd"인 경우 결과는 "a" 및 "def"입니다.
성능 고려 사항
메서드는 Split 반환된 배열 개체에 대한 메모리와 String 각 배열 요소에 대한 개체를 할당합니다. 애플리케이션에 필요한 최적의 성능, 메모리 할당을 관리 하는 것이 중요 애플리케이션 사용을 고려 합니다 IndexOf 또는 IndexOfAny 메서드 및 필요에 따라는 Compare 문자열 내에서 부분 문자열을 찾을 방법입니다.
구분 기호 문자로 문자열을 분할하는 경우 또는 IndexOfAny 메서드를 IndexOf 사용하여 문자열에서 구분 기호 문자를 찾습니다. 구분 기호 문자열에서 문자열을 분할하는 경우 또는 IndexOfAny 메서드를 IndexOf 사용하여 구분 기호 문자열의 첫 번째 문자를 찾습니다. 그런 다음 메서드를 Compare 사용하여 첫 번째 문자 뒤에 있는 문자가 구분 기호 문자열의 나머지 문자와 같은지 여부를 확인합니다.
또한 여러 Split 메서드 호출에서 문자열을 분할하는 데 동일한 문자 집합을 사용하는 경우 단일 배열을 만들고 각 메서드 호출에서 참조하는 것이 좋습니다. 이렇게 하면 각 메서드 호출의 추가 오버헤드가 크게 줄어듭니다.
호출자 참고
.NET Framework 3.5 이전 버전에서 메서드가 전달되거나 separator
문자가 없는 경우 Split(Char[]) 메서드는 null
약간 다른 공백 문자 집합을 사용하여 메서드가 문자열을 자르는 것과는 다른 Trim(Char[]) 문자열을 분할합니다. .NET Framework 4부터 두 메서드 모두 동일한 유니코드 공백 문자 집합을 사용합니다.
적용 대상
Split(Char[], StringSplitOptions)
- Source:
- String.Manipulation.cs
- Source:
- String.Manipulation.cs
- Source:
- String.Manipulation.cs
지정된 구분 문자 및 옵션에 따라 문자열을 부분 문자열로 분할합니다.
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()
매개 변수
- separator
- Char[]
이 문자열의 부분 문자열을 구분하는 문자 배열, 구분 기호를 포함하지 않는 빈 배열 또는 null
입니다.
- options
- StringSplitOptions
부분 문자열을 자르고 빈 부분 문자열을 포함할지를 지정하는 열거형 값의 비트 조합입니다.
반환
해당 요소에 separator
에 있는 하나 이상의 문자로 구분되는 이 문자열의 부분 문자열이 포함된 배열입니다. 자세한 내용은 주의 섹션을 참조하세요.
- 특성
예외
options
가 StringSplitOptions 값 중 하나가 아닙니다.
예제
다음 예제에서는 열거형을 사용하여 StringSplitOptions 메서드에서 생성된 Split 부분 문자열을 포함하거나 제외합니다.
// This example demonstrates the String.Split(Char[], Boolean) and
// String.Split(Char[], Int32, Boolean) methods
using namespace System;
void Show( array<String^>^entries )
{
Console::WriteLine( "The return value contains these {0} elements:", entries->Length );
System::Collections::IEnumerator^ myEnum = entries->GetEnumerator();
while ( myEnum->MoveNext() )
{
String^ entry = safe_cast<String^>(myEnum->Current);
Console::Write( "<{0}>", entry );
}
Console::Write( "{0}{0}", Environment::NewLine );
}
int main()
{
String^ s = ",one,,,two,,,,,three,,";
array<Char>^sep = gcnew array<Char>{
','
};
array<String^>^result;
//
Console::WriteLine( "The original string is \"{0}\".", s );
Console::WriteLine( "The separation character is '{0}'.", sep[ 0 ] );
Console::WriteLine();
//
Console::WriteLine( "Split the string and return all elements:" );
result = s->Split( sep, StringSplitOptions::None );
Show( result );
//
Console::WriteLine( "Split the string and return all non-empty elements:" );
result = s->Split( sep, StringSplitOptions::RemoveEmptyEntries );
Show( result );
//
Console::WriteLine( "Split the string and return 2 elements:" );
result = s->Split( sep, 2, StringSplitOptions::None );
Show( result );
//
Console::WriteLine( "Split the string and return 2 non-empty elements:" );
result = s->Split( sep, 2, StringSplitOptions::RemoveEmptyEntries );
Show( result );
}
/*
This example produces the following results:
The original string is ",one,,,two,,,,,three,,".
The separation character is ','.
Split the string and return all elements:
The return value contains these 12 elements:
<><one><><><two><><><><><three><><>
Split the string and return all non-empty elements:
The return value contains these 3 elements:
<one><two><three>
Split the string and return 2 elements:
The return value contains these 2 elements:
<><one,,,two,,,,,three,,>
Split the string and return 2 non-empty elements:
The return value contains these 2 elements:
<one><,,two,,,,,three,,>
*/
// This example demonstrates the String.Split() methods that use
// the StringSplitOptions enumeration.
// 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]>
'
설명
구분 기호 문자(배열의 separator
문자)는 반환된 배열의 요소에 포함되지 않습니다. 예를 들어 배열에 separator
"-" 문자가 포함되고 현재 문자열 instance 값이 "aa-bb-cc"인 경우 메서드는 "aa", "bb" 및 "cc"의 세 가지 요소가 포함된 배열을 반환합니다.
이 instance 의 separator
문자를 포함하지 않는 경우 반환된 배열은 이 instance 포함하는 단일 요소로 구성됩니다.
매개 변수가 options
이 RemoveEmptyEntries 고 이 instance 길이가 0이면 메서드는 빈 배열을 반환합니다.
의 separator
각 요소는 단일 문자로 구성된 별도의 구분 기호를 정의합니다. 인수가 options
None이고 두 개의 구분 기호가 인접하거나 이 instance 시작 또는 끝에 구분 기호가 있는 경우 해당 배열 요소에 가 포함됩니다String.Empty. 예를 들어 및 라는 두 요소가 '-'
'_'
포함된 경우 separator
문자열 instance 값은 "-_aa-_"이고 인수 값 options
은 입니다. 메서드는 None다음 5개의 요소가 포함된 문자열 배열을 반환합니다.
String.Empty인덱스 0에서 "-" 문자 앞에 오는 빈 문자열을 나타냅니다.
String.Empty인덱스 0의 "-" 문자와 인덱스 1의 "_" 문자 사이의 빈 문자열을 나타내는 입니다.
"aa".
String.Empty인덱스 4의 "-" 문자 뒤에 있는 빈 문자열을 나타냅니다.
String.Empty인덱스 5의 "_" 문자 뒤에 있는 빈 문자열을 나타내는 입니다.
구분 기호 배열
매개 변수가 separator
이거나 null
문자를 포함하지 않는 경우 공백 문자는 구분 기호로 간주됩니다. 공백 문자는 유니코드 표준에 의해 정의되고 메서드는 Char.IsWhiteSpace 전달되면 를 반환 true
합니다.
매개 변수에 char[] separator
대해 를 전달 null
하려면 와 같은 Split(String[], StringSplitOptions)다른 오버로드에서 호출을 명확하게 하기 위해 의 null
형식을 나타내야 합니다. 다음 예제에서는 이 오버로드를 명확하게 식별하는 여러 가지 방법을 보여줍니다.
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)
비교 세부 정보
메서드는 Split 매개 변수의 하나 이상의 문자 separator
로 구분된 이 문자열의 부분 문자열을 추출하고 해당 부분 문자열을 배열의 요소로 반환합니다.
메서드는 Split 대/소문자를 구분하는 서수 정렬 규칙을 사용하여 비교를 수행하여 구분 기호를 찾습니다. 단어, 문자열 및 서수 정렬에 대한 자세한 내용은 열거형을 System.Globalization.CompareOptions 참조하세요.
성능 고려 사항
메서드는 Split 반환된 배열 개체에 대한 메모리와 String 각 배열 요소에 대한 개체를 할당합니다. 애플리케이션에 필요한 최적의 성능, 메모리 할당을 관리 하는 것이 중요 애플리케이션 사용을 고려 합니다 IndexOf 또는 IndexOfAny 메서드 및 필요에 따라는 Compare 문자열 내에서 부분 문자열을 찾을 방법입니다.
구분 기호 문자로 문자열을 분할하는 경우 또는 IndexOfAny 메서드를 IndexOf 사용하여 문자열에서 구분 기호 문자를 찾습니다. 구분 기호 문자열에서 문자열을 분할하는 경우 또는 IndexOfAny 메서드를 IndexOf 사용하여 구분 기호 문자열의 첫 번째 문자를 찾습니다. 그런 다음 메서드를 Compare 사용하여 첫 번째 문자 뒤에 있는 문자가 구분 기호 문자열의 나머지 문자와 같은지 여부를 확인합니다.
또한 여러 Split 메서드 호출에서 문자열을 분할하는 데 동일한 문자 집합을 사용하는 경우 단일 배열을 만들고 각 메서드 호출에서 참조하는 것이 좋습니다. 이렇게 하면 각 메서드 호출의 추가 오버헤드가 크게 줄어듭니다.
호출자 참고
.NET Framework 3.5 및 이전 버전에서 메서드가 전달되거나 separator
문자가 null
없는 경우 Split(Char[]) 메서드는 약간 다른 공백 문자 집합을 사용하여 문자열 Trim(Char[]) 을 자르기 위해 메서드와는 약간 다른 문자열을 분할합니다. .NET Framework 4부터 두 메서드 모두 동일한 유니코드 공백 문자 집합을 사용합니다.
적용 대상
.NET
피드백
https://aka.ms/ContentUserFeedback
출시 예정: 2024년 내내 콘텐츠에 대한 피드백 메커니즘으로 GitHub 문제를 단계적으로 폐지하고 이를 새로운 피드백 시스템으로 바꿀 예정입니다. 자세한 내용은 다음을 참조하세요.다음에 대한 사용자 의견 제출 및 보기