String.Split メソッド

定義

このインスタンス内の、指定された文字列または Unicode 文字の配列の要素で区切られた部分文字列を格納する文字列配列を返します。

オーバーロード

Split(Char[])

指定した区切り文字に基づいて、文字列を部分文字列に分割します。

Split(Char, StringSplitOptions)

指定された 1 つの区切り文字およびオプション (任意) に基づいて文字列を部分文字列に分割します。

Split(Char[], Int32)

指定した区切り文字に基づいて、文字列を部分文字列の最大数に分割します。

Split(Char[], StringSplitOptions)

指定した区切り文字とオプションに基づいて、文字列を部分文字列に分割します。

Split(String, StringSplitOptions)

指定された文字列の区切り記号に基づいて文字列を部分文字列に分割します。

Split(String[], StringSplitOptions)

指定された 1 つの区切り文字列およびオプション (任意) に基づいて文字列を部分文字列に分割します。

Split(Char, Int32, StringSplitOptions)

指定された 1 つの区切り文字およびオプション (任意) に基づいて文字列を最大数の部分文字列に分割します。 指定された文字区切り記号に基づいて文字列を最大数の部分文字列に分割します。オプションで、結果からの空の部分文字列を省略します。

Split(Char[], Int32, StringSplitOptions)

指定された区切り文字およびオプション (任意) に基づいて文字列を最大数の部分文字列に分割します。

Split(String, Int32, StringSplitOptions)

指定された 1 つの区切り文字列およびオプション (任意) に基づいて文字列を最大数の部分文字列に分割します。

Split(String[], Int32, StringSplitOptions)

指定された区切り文字列およびオプション (任意) に基づいて文字列を最大数の部分文字列に分割します。

注釈

Split は、区切られた文字列を部分文字列に分割するために使用されます。 文字配列または文字列配列を使用して、0 個以上の区切り文字または文字列を指定できます。 区切り文字が指定されていない場合、文字列は空白文字で分割されます。

メソッドのSplitオーバーロードを使用すると、メソッド (Split(Char[], Int32)メソッド) によって返される部分文字列の数を制限して、空の文字列やトリミング部分文字列を結果 (メソッドと Split(String[], StringSplitOptions) メソッド) に含めるか、両方を実行するかを指定できます (Split(Char[], StringSplitOptions)Split(Char[], Int32, StringSplitOptions)メソッドと Split(String[], Int32, StringSplitOptions) メソッド)。

ヒント

メソッドは Split 、区切られた文字列を部分文字列に分割する最善の方法であるとは限りません。 区切り文字列のすべての部分文字列を抽出しない場合、または区切り文字のセットではなくパターンに基づいて文字列を解析する場合は、正規表現を使用するか、文字のインデックスを返す検索メソッドの 1 つを メソッドと Substring 組み合わせることを検討してください。 詳細については、「 文字列から部分文字列を抽出する」を参照してください。

次の例では、String.Split() の 3 つの異なるオーバーロードを示します。 最初の例では、 オーバーロードを Split(Char[]) 呼び出し、1 つの区切り記号を渡します。

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.

ご覧のように、部分文字列の 2 つにピリオド文字 (.) が含まれています。 ピリオド文字を除外する場合は、ピリオド文字を追加の区切り文字として追加できます。 その方法を次の例に示します。

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:

部分文字列からピリオドは削除されましたが、今度は 2 つの余分な空の部分文字列が含まれるようになっています。 これらの空の部分文字列は、単語とその後のピリオドの間の部分文字列を表します。 結果の配列から空の部分文字列を省略するには、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(Char[])

指定した区切り文字に基づいて、文字列を部分文字列に分割します。

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

戻り値

String[]

このインスタンスを separator の 1 つ以上の文字で区切った部分文字列を要素に格納する配列。 詳細については、「解説」を参照してください。

次の例では、スペース文字 () とタブ文字 ( \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[]) 使用して部分文字列に区切ることができます。

返される配列の要素には区切り文字は含まれません。 たとえば、区切り文字配列に文字 "-" が含まれており、現在の文字列インスタンスの値が "aa-bb-cc" の場合、メソッドは"aa"、"bb"、および "cc" の 3 つの要素を含む配列を返します。

このインスタンスに の文字 separatorが含まれていない場合、返される配列は、このインスタンスを含む 1 つの要素で構成されます。

の各要素は separator 、個別の区切り文字を定義します。 2 つの区切り記号が隣接している場合、またはこのインスタンスの先頭または末尾に区切り記号が見つかった場合、返される配列の対応する要素には が Empty含まれます。

次の表に例を示します。

Language 文字列値 区切り記号 返される配列
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[] {'.'} {"バナナ"}
Visual Basic "バナナ" Char() = {"."c} {"バナナ"}
C# "Darb\nSmarba" new Char[] {} {"Darb", "Smarba"}
Visual Basic "Darb" & vbLf & "Smarba" Char() = {} {"Darb", "Smarba"}
C# "Darb\nSmarba" null {"Darb", "Smarba"}
Visual Basic "Darb" & vbLf & "Smarba" なし {"Darb", "Smarba"}

区切り文字の配列

区切り記号の各要素は、1 つの文字で構成される個別の区切り記号を定義します。

引数が separator または null に文字を含まない場合、メソッドは空白文字を区切り記号として扱います。 空白文字は Unicode 標準で定義され Char.IsWhiteSpace 、空白文字が渡された場合、 メソッドは を返 true します。

String.Split(Char[]) とコンパイラ オーバーロードの解決

この オーバーロードの単一パラメーターは文字配列ですが、次の String.Split 例に示すように、1 つの文字で呼び出すことができます。

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修飾されているため、コンパイラは 1 つの文字を単一要素の文字配列として解釈します。 これは、パラメーターを含むseparatorString.Splitのオーバーロードの場合ではありません。これらのオーバーロードを引数としてseparator文字配列を明示的に渡す必要があります。

比較の詳細

メソッドは Split(Char[]) 、配列内の 1 つ以上の文字で区切られたこの文字列内の部分文字列を separator 抽出し、それらの部分文字列を配列の要素として返します。

メソッドは Split(Char[]) 、大文字と小文字を区別する序数の並べ替え規則を使用して比較を実行することで、区切り記号を検索します。 単語、文字列、序数の並べ替えの詳細については、 列挙を System.Globalization.CompareOptions 参照してください。

パフォーマンスに関する考慮事項

メソッドは Split 、返された配列オブジェクトにメモリを割り当て、 String 配列要素ごとに オブジェクトを割り当てます。 アプリケーションで最適なパフォーマンスが必要な場合、またはアプリケーションでメモリ割り当ての管理が重要な場合は、 メソッドまたは IndexOfAny メソッドの使用をIndexOf検討してください。 また、 メソッドを使用して Compare 文字列内の部分文字列を検索することもできます。

区切り文字で文字列を分割するには、 メソッドまたは IndexOfAny メソッドをIndexOf使用して、文字列内の区切り文字を検索します。 区切り文字列で文字列を分割するには、 メソッドまたは IndexOfAny メソッドをIndexOf使用して、区切り文字列の最初の文字を見つけます。 次に、 メソッドを Compare 使用して、最初の文字の後の文字が区切り文字の残りの文字と等しいかどうかを判断します。

さらに、同じ文字セットを使用して複数 Split のメソッド呼び出しで文字列を分割する場合は、1 つの配列を作成し、各メソッド呼び出しでそれを参照することを検討してください。 これにより、各メソッド呼び出しの追加オーバーヘッドが大幅に削減されます。

注意 (呼び出し元)

.NET Framework 3.5 以前のバージョンでは、 メソッドに が渡されたnullseparator場合、または文字が含まれていない場合Split(Char[])、メソッドは文字列をトリミングする場合とはTrim(Char[])少し異なる空白文字のセットを使用して文字列を分割します。 .NET Framework 4 以降では、両方のメソッドで同じ Unicode 空白文字のセットが使用されます。

こちらもご覧ください

適用対象

Split(Char, StringSplitOptions)

指定された 1 つの区切り文字およびオプション (任意) に基づいて文字列を部分文字列に分割します。

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

部分文字列をトリミングして空の部分文字列を含めるかどうかを指定する列挙値のビットごとの組み合わせ。

戻り値

String[]

separator によって区切られた、このインスタンスの部分文字列を要素に格納する配列。

適用対象

Split(Char[], Int32)

指定した区切り文字に基づいて、文字列を部分文字列の最大数に分割します。

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

返される最大の部分文字列数。

戻り値

String[]

このインスタンスを、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(Nothing, 2)
Dim firstName As String = substrings(0)
Dim lastName As String

If substrings.Length > 1 Then
    lastName = substrings(1)
End If

' If the user enters "Alex Johnson III":
' firstName = "Alex"
' lastName = "Johnson III"

注釈

区切り文字は、返される配列の要素には含まれません。

このインスタンスに の文字が含まれていない場合、返される配列は、このインスタンスを含む 1 つの要素で separator構成されます。 が 0 の場合 count は、空の配列が返されます。

パラメーターが separator または null に文字を含まない場合、空白文字は区切り記号と見なされます。 空白文字は Unicode 標準によって定義され、 Char.IsWhiteSpace メソッドは渡された場合に を返 true します。

separator 各要素は、個別の区切り文字を定義します。 2 つの区切り記号が隣接している場合、またはこのインスタンスの先頭または末尾に区切り記号が見つかった場合、対応する配列要素には が含まれます Empty

このインスタンスに複数 count の部分文字列がある場合、最初 count - 1 の部分文字列は戻り値の最初 count - 1 の要素で返され、このインスタンスの残りの文字は戻り値の最後の要素で返されます。

が部分文字列の数より大きい場合 count は、使用可能な部分文字列が返され、例外はスローされません。

次の表に例を示します。

Language 文字列値 区切り記号 返される配列
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# "Darb\nSmarba" new Char[] {} {"Darb", "Smarba"}
Visual Basic "Darb" & vbLf & "Smarba" Char() = {} {"Darb", "Smarba"}
C# "Darb\nSmarba" null {"Darb", "Smarba"}
Visual Basic "Darb" & vbLf & "Smarba" なし {"Darb", "Smarba"}

パフォーマンスに関する考慮事項

メソッドは Split 、返された配列オブジェクトにメモリを割り当て、各配列要素に String オブジェクトを割り当てます。 アプリケーションで最適なパフォーマンスが必要な場合、またはアプリケーションでメモリ割り当ての管理が重要な場合は、 メソッドまたは IndexOfAny メソッドを使用し、必要に応じて メソッドをCompare使用IndexOfして文字列内の部分文字列を検索することを検討してください。

区切り文字で文字列を分割する場合は、 メソッドまたは IndexOfAny メソッドをIndexOf使用して、文字列内の区切り文字を見つけます。 区切り文字列で文字列を分割する場合は、 メソッドまたは IndexOfAny メソッドをIndexOf使用して、区切り文字列の最初の文字を見つけます。 次に、 メソッドを Compare 使用して、最初の文字の後の文字が区切り文字の残りの文字と等しいかどうかを判断します。

さらに、同じ文字セットを使用して複数 Split のメソッド呼び出しで文字列を分割する場合は、1 つの配列を作成し、各メソッド呼び出しでそれを参照することを検討してください。 これにより、各メソッド呼び出しの追加オーバーヘッドが大幅に削減されます。

注意 (呼び出し元)

.NET Framework 3.5 以前のバージョンでは、 メソッドに が渡されたnullseparator場合、または文字が含まれていない場合Split(Char[])、メソッドは文字列をトリミングする場合とはTrim(Char[])少し異なる空白文字のセットを使用して文字列を分割します。 .NET Framework 4 以降では、両方のメソッドで同じ Unicode 空白文字のセットが使用されます。

こちらもご覧ください

適用対象

Split(Char[], StringSplitOptions)

指定した区切り文字とオプションに基づいて、文字列を部分文字列に分割します。

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

部分文字列をトリミングして空の部分文字列を含めるかどうかを指定する列挙値のビットごとの組み合わせ。

戻り値

String[]

この文字列を、separator 配列のいずれかまたは複数の要素 (文字) で区切ることによって取り出された部分文字列を格納する配列。 詳細については、「解説」を参照してください。

属性

例外

optionsStringSplitOptions 値のいずれでもありません。

次の例では、 列挙を 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.
string s1 = ",ONE,,TWO,,,THREE,,";
string s2 = "[stop]" +
            "ONE[stop][stop]" +
            "TWO[stop][stop][stop]" +
            "THREE[stop][stop]";
char[] charSeparators = new char[] { ',' };
string[] stringSeparators = new string[] { "[stop]" };
string[] result;
// ------------------------------------------------------------------------------
// Split a string delimited by characters.
// ------------------------------------------------------------------------------
Console.WriteLine("1) Split a string delimited by characters:\n");

// Display the original string and delimiter characters.
Console.WriteLine($"1a) The original string is \"{s1}\".");
Console.WriteLine($"The delimiter character is '{charSeparators[0]}'.\n");

// Split a string delimited by characters and return all elements.
Console.WriteLine("1b) Split a string delimited by characters and " +
                  "return all elements:");
result = s1.Split(charSeparators, StringSplitOptions.None);
Show(result);

// Split a string delimited by characters and return all non-empty elements.
Console.WriteLine("1c) Split a string delimited by characters and " +
                  "return all non-empty elements:");
result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);
Show(result);

// Split the original string into the string and empty string before the
// delimiter and the remainder of the original string after the delimiter.
Console.WriteLine("1d) Split a string delimited by characters and " +
                  "return 2 elements:");
result = s1.Split(charSeparators, 2, StringSplitOptions.None);
Show(result);

// Split the original string into the string after the delimiter and the
// remainder of the original string after the delimiter.
Console.WriteLine("1e) Split a string delimited by characters and " +
                  "return 2 non-empty elements:");
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries);
Show(result);

// ------------------------------------------------------------------------------
// Split a string delimited by another string.
// ------------------------------------------------------------------------------
Console.WriteLine("2) Split a string delimited by another string:\n");

// Display the original string and delimiter string.
Console.WriteLine($"2a) The original string is \"{s2}\".");
Console.WriteLine($"The delimiter string is \"{stringSeparators[0]}\".\n");

// Split a string delimited by another string and return all elements.
Console.WriteLine("2b) Split a string delimited by another string and " +
                  "return all elements:");
result = s2.Split(stringSeparators, StringSplitOptions.None);
Show(result);

// Split the original string at the delimiter and return all non-empty elements.
Console.WriteLine("2c) Split a string delimited by another string and " +
                  "return all non-empty elements:");
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);
Show(result);

// Split the original string into the empty string before the
// delimiter and the remainder of the original string after the delimiter.
Console.WriteLine("2d) Split a string delimited by another string and " +
                  "return 2 elements:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.None);
Show(result);

// Split the original string into the string after the delimiter and the
// remainder of the original string after the delimiter.
Console.WriteLine("2e) Split a string delimited by another string and " +
                  "return 2 non-empty elements:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries);
Show(result);

// Display the array of separated strings using a local function
void Show(string[] entries)
{
    Console.WriteLine($"The return value contains these {entries.Length} elements:");
    foreach (string entry in entries)
    {
        Console.Write($"<{entry}>");
    }
    Console.Write("\n\n");
}

/*
This example produces the following results:

1) Split a string delimited by characters:

1a) The original string is ",ONE,,TWO,,,THREE,,".
The delimiter character is ','.

1b) Split a string delimited by characters and return all elements:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>

1c) Split a string delimited by characters and return all non-empty elements:
The return value contains these 3 elements:
<ONE><TWO><THREE>

1d) Split a string delimited by characters and return 2 elements:
The return value contains these 2 elements:
<><ONE,,TWO,,,THREE,,>

1e) Split a string delimited by characters and return 2 non-empty elements:
The return value contains these 2 elements:
<ONE><TWO,,,THREE,,>

2) Split a string delimited by another string:

2a) The original string is "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".
The delimiter string is "[stop]".

2b) Split a string delimited by another string and return all elements:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>

2c) Split a string delimited by another string and return all non-empty elements:
The return value contains these 3 elements:
<ONE><TWO><THREE>

2d) Split a string delimited by another string and return 2 elements:
The return value contains these 2 elements:
<><ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]>

2e) Split a string delimited by another string and return 2 non-empty elements:
The return value contains these 2 elements:
<ONE><TWO[stop][stop][stop]THREE[stop][stop]>

*/
// This example demonstrates the String.Split() methods that use
// the StringSplitOptions enumeration.
 
// Display the array of separated strings using a local function
let show  (entries: string[]) =
    printfn $"The return value contains these {entries.Length} elements:"
    for entry in entries do
        printf $"<{entry}>"
    printf "\n\n"

let s1 = ",ONE,,TWO,,,THREE,,"
let s2 = "[stop]" +
         "ONE[stop][stop]" +
         "TWO[stop][stop][stop]" +
         "THREE[stop][stop]"
let charSeparators = [| ',' |]
let stringSeparators = [| "[stop]" |]
// ------------------------------------------------------------------------------
// Split a string delimited by characters.
// ------------------------------------------------------------------------------
printfn "1) Split a string delimited by characters:\n"

// Display the original string and delimiter characters.
printfn $"1a) The original string is \"{s1}\"."
printfn $"The delimiter character is '{charSeparators[0]}'.\n"

// Split a string delimited by characters and return all elements.
printfn "1b) Split a string delimited by characters and return all elements:"
let result = s1.Split(charSeparators, StringSplitOptions.None)
show result

// Split a string delimited by characters and return all non-empty elements.
printfn "1c) Split a string delimited by characters and return all non-empty elements:"
let result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries)
show result

// Split the original string into the string and empty string before the
// delimiter and the remainder of the original string after the delimiter.
printfn "1d) Split a string delimited by characters and return 2 elements:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.None)
show result

// Split the original string into the string after the delimiter and the
// remainder of the original string after the delimiter.
printfn "1e) Split a string delimited by characters and return 2 non-empty elements:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
show result

// ------------------------------------------------------------------------------
// Split a string delimited by another string.
// ------------------------------------------------------------------------------
printfn "2) Split a string delimited by another string:\n"

// Display the original string and delimiter string.
printfn $"2a) The original string is \"{s2}\"."
printfn $"The delimiter string is \"{stringSeparators[0]}\".\n"

// Split a string delimited by another string and return all elements.
printfn "2b) Split a string delimited by another string and return all elements:"
let result = s2.Split(stringSeparators, StringSplitOptions.None)
show result

// Split the original string at the delimiter and return all non-empty elements.
printfn "2c) Split a string delimited by another string and return all non-empty elements:"
let result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)
show result

// Split the original string into the empty string before the
// delimiter and the remainder of the original string after the delimiter.
printfn "2d) Split a string delimited by another string and return 2 elements:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.None)
show result

// Split the original string into the string after the delimiter and the
// remainder of the original string after the delimiter.
printfn "2e) Split a string delimited by another string and return 2 non-empty elements:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
show result

(*
This example produces the following results:

1) Split a string delimited by characters:

1a) The original string is ",ONE,,TWO,,,THREE,,".
The delimiter character is ','.

1b) Split a string delimited by characters and return all elements:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>

1c) Split a string delimited by characters and return all non-empty elements:
The return value contains these 3 elements:
<ONE><TWO><THREE>

1d) Split a string delimited by characters and return 2 elements:
The return value contains these 2 elements:
<><ONE,,TWO,,,THREE,,>

1e) Split a string delimited by characters and return 2 non-empty elements:
The return value contains these 2 elements:
<ONE><TWO,,,THREE,,>

2) Split a string delimited by another string:

2a) The original string is "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".
The delimiter string is "[stop]".

2b) Split a string delimited by another string and return all elements:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>

2c) Split a string delimited by another string and return all non-empty elements:
The return value contains these 3 elements:
<ONE><TWO><THREE>

2d) Split a string delimited by another string and return 2 elements:
The return value contains these 2 elements:
<><ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]>

2e) Split a string delimited by another string and return 2 non-empty elements:
The return value contains these 2 elements:
<ONE><TWO[stop][stop][stop]THREE[stop][stop]>

*)
    Dim s1 As String = ",ONE,,TWO,,,THREE,,"
    Dim s2 As String = "[stop]" &
                       "ONE[stop][stop]" &
                       "TWO[stop][stop][stop]" &
                       "THREE[stop][stop]"
    Dim charSeparators() As Char = {","c}
    Dim stringSeparators() As String = {"[stop]"}
    Dim result() As String
    ' ------------------------------------------------------------------------------
    ' Split a string delimited by characters.
    ' ------------------------------------------------------------------------------
    Console.WriteLine("1) Split a string delimited by characters:" & vbCrLf)

    ' Display the original string and delimiter characters.
    Console.WriteLine("1a) The original string is ""{0}"".", s1)
    Console.WriteLine("The delimiter character is '{0}'." & vbCrLf, charSeparators(0))

    ' Split a string delimited by characters and return all elements.
    Console.WriteLine("1b) Split a string delimited by characters and " &
                      "return all elements:")
    result = s1.Split(charSeparators, StringSplitOptions.None)
    Show(result)

    ' Split a string delimited by characters and return all non-empty elements.
    Console.WriteLine("1c) Split a string delimited by characters and " &
                      "return all non-empty elements:")
    result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries)
    Show(result)

    ' Split the original string into the string and empty string before the 
    ' delimiter and the remainder of the original string after the delimiter.
    Console.WriteLine("1d) Split a string delimited by characters and " &
                      "return 2 elements:")
    result = s1.Split(charSeparators, 2, StringSplitOptions.None)
    Show(result)

    ' Split the original string into the string after the delimiter and the 
    ' remainder of the original string after the delimiter.
    Console.WriteLine("1e) Split a string delimited by characters and " &
                      "return 2 non-empty elements:")
    result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
    Show(result)

    ' ------------------------------------------------------------------------------
    ' Split a string delimited by another string.
    ' ------------------------------------------------------------------------------
    Console.WriteLine("2) Split a string delimited by another string:" & vbCrLf)

    ' Display the original string and delimiter string.
    Console.WriteLine("2a) The original string is ""{0}"".", s2)
    Console.WriteLine("The delimiter string is ""{0}""." & vbCrLf, stringSeparators(0))

    ' Split a string delimited by another string and return all elements.
    Console.WriteLine("2b) Split a string delimited by another string and " &
                      "return all elements:")
    result = s2.Split(stringSeparators, StringSplitOptions.None)
    Show(result)

    ' Split the original string at the delimiter and return all non-empty elements.
    Console.WriteLine("2c) Split a string delimited by another string and " &
                      "return all non-empty elements:")
    result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)
    Show(result)

    ' Split the original string into the empty string before the 
    ' delimiter and the remainder of the original string after the delimiter.
    Console.WriteLine("2d) Split a string delimited by another string and " &
                      "return 2 elements:")
    result = s2.Split(stringSeparators, 2, StringSplitOptions.None)
    Show(result)

    ' Split the original string into the string after the delimiter and the 
    ' remainder of the original string after the delimiter.
    Console.WriteLine("2e) Split a string delimited by another string and " &
                      "return 2 non-empty elements:")
    result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
    Show(result)

End Sub


' Display the array of separated strings.
Public Shared Sub Show(ByVal entries() As String)
    Console.WriteLine("The return value contains these {0} elements:", entries.Length)
    Dim entry As String
    For Each entry In entries
        Console.Write("<{0}>", entry)
    Next entry
    Console.Write(vbCrLf & vbCrLf)

End Sub

'This example produces the following results:
'
'1) Split a string delimited by characters:
'
'1a) The original string is ",ONE,,TWO,,,THREE,,".
'The delimiter character is ','.
'
'1b) Split a string delimited by characters and return all elements:
'The return value contains these 9 elements:
'<><ONE><><TWO><><><THREE><><>
'
'1c) Split a string delimited by characters and return all non-empty elements:
'The return value contains these 3 elements:
'<ONE><TWO><THREE>
'
'1d) Split a string delimited by characters and return 2 elements:
'The return value contains these 2 elements:
'<><ONE,,TWO,,,THREE,,>
'
'1e) Split a string delimited by characters and return 2 non-empty elements:
'The return value contains these 2 elements:
'<ONE><TWO,,,THREE,,>
'
'2) Split a string delimited by another string:
'
'2a) The original string is "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".
'The delimiter string is "[stop]".
'
'2b) Split a string delimited by another string and return all elements:
'The return value contains these 9 elements:
'<><ONE><><TWO><><><THREE><><>
'
'2c) Split a string delimited by another string and return all non-empty elements:
'The return value contains these 3 elements:
'<ONE><TWO><THREE>
'
'2d) Split a string delimited by another string and return 2 elements:
'The return value contains these 2 elements:
'<><ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]>
'
'2e) Split a string delimited by another string and return 2 non-empty elements:
'The return value contains these 2 elements:
'<ONE><TWO[stop][stop][stop]THREE[stop][stop]>
'

注釈

区切り文字 (配列内の separator 文字) は、返される配列の要素には含まれません。 たとえば、配列に separator 文字 "-" が含まれており、現在の文字列インスタンスの値が "aa-bb-cc" の場合、メソッドは"aa"、"bb"、"cc" の 3 つの要素を含む配列を返します。

このインスタンスに の文字が含まれていない場合、返される配列は、このインスタンスを含む 1 つの要素で separator構成されます。

パラメーターが optionsRemoveEmptyEntries 、このインスタンスの長さが 0 の場合、メソッドは空の配列を返します。

separator 各要素は、1 つの文字で構成される個別の区切り記号を定義します。 引数が optionsNone、2 つの区切り記号が隣接している場合、またはこのインスタンスの先頭または末尾に区切り記号が見つかった場合、対応する配列要素には が含まれます String.Empty。 たとえば、 と '_'の 2 つの要素が含まれている場合separator'-'文字列インスタンスの値は "-_aa-_" で、 引数の値は です。メソッドはNone、次の options 5 つの要素を含む文字列配列を返します。

  1. String.Emptyは、インデックス 0 の "-" 文字の前にある空の文字列を表します。

  2. String.Emptyは、インデックス 0 の "-" 文字とインデックス 1 の "_" 文字の間の空の文字列を表します。

  3. "aa"

  4. String.Emptyは、インデックス 4 の "-" 文字に続く空の文字列を表します。

  5. String.Emptyは、インデックス 5 の "_" 文字に続く空の文字列を表します。

区切り記号配列

パラメーターが separator または null に文字を含まない場合、空白文字は区切り記号と見なされます。 空白文字は Unicode 標準によって定義され、 Char.IsWhiteSpace メソッドは渡された場合に を返 true します。

パラメーターに を渡nullすには、 などのSplit(String[], StringSplitOptions)他のいくつかのnullオーバーロードからの呼び出しを明確にするために、 の型を指定する必要char[] separatorがあります。 次の例は、このオーバーロードを明確に識別するいくつかの方法を示しています。

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 、 パラメーター内の 1 つ以上の文字で区切られたこの文字列内の部分文字列を separator 抽出し、それらの部分文字列を配列の要素として返します。

メソッドは Split 、大文字と小文字を区別する序数の並べ替え規則を使用して比較を実行することで、区切り記号を検索します。 単語、文字列、および序数の並べ替えの詳細については、 列挙を System.Globalization.CompareOptions 参照してください。

パフォーマンスに関する考慮事項

メソッドは Split 、返された配列オブジェクトにメモリを割り当て、各配列要素に String オブジェクトを割り当てます。 アプリケーションで最適なパフォーマンスが必要な場合、またはアプリケーションでメモリ割り当ての管理が重要な場合は、 メソッドまたは IndexOfAny メソッドを使用し、必要に応じて メソッドをCompare使用IndexOfして文字列内の部分文字列を検索することを検討してください。

区切り文字で文字列を分割する場合は、 メソッドまたは IndexOfAny メソッドをIndexOf使用して、文字列内の区切り文字を見つけます。 区切り文字列で文字列を分割する場合は、 メソッドまたは IndexOfAny メソッドをIndexOf使用して、区切り文字列の最初の文字を見つけます。 次に、 メソッドを Compare 使用して、最初の文字の後の文字が区切り文字の残りの文字と等しいかどうかを判断します。

さらに、同じ文字セットを使用して複数 Split のメソッド呼び出しで文字列を分割する場合は、1 つの配列を作成し、各メソッド呼び出しでそれを参照することを検討してください。 これにより、各メソッド呼び出しの追加オーバーヘッドが大幅に削減されます。

注意 (呼び出し元)

.NET Framework 3.5 以前のバージョンでは、 メソッドに が渡されたnullseparator場合、または文字が含まれていない場合Split(Char[])、メソッドは文字列をトリミングする場合とはTrim(Char[])少し異なる空白文字のセットを使用して文字列を分割します。 .NET Framework 4 以降では、両方のメソッドで同じ Unicode 空白文字のセットが使用されます。

適用対象

Split(String, StringSplitOptions)

指定された文字列の区切り記号に基づいて文字列を部分文字列に分割します。

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

部分文字列をトリミングして空の部分文字列を含めるかどうかを指定する列挙値のビットごとの組み合わせ。

戻り値

String[]

separator によって区切られた、このインスタンスの部分文字列を要素に格納する配列。

適用対象

Split(String[], StringSplitOptions)

指定された 1 つの区切り文字列およびオプション (任意) に基づいて文字列を部分文字列に分割します。

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

部分文字列をトリミングして空の部分文字列を含めるかどうかを指定する列挙値のビットごとの組み合わせ。

戻り値

String[]

この文字列を、separator 配列のいずれかまたは複数の要素 (文字列) で区切ることによって取り出された部分文字列を格納する配列。 詳細については、「解説」を参照してください。

属性

例外

optionsStringSplitOptions 値のいずれでもありません。

次の例は、 と 等しいパラメーターを使用optionsして文字列の メソッドを呼び出すことによって返される配列のString.Split(String[], StringSplitOptions)違いをStringSplitOptions.NoneStringSplitOptions.RemoveEmptyEntries示しています。

string source = "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]";
string[] stringSeparators = new string[] { "[stop]" };
string[] result;

// Display the original string and delimiter string.
Console.WriteLine($"Splitting the string:\n   \"{source}\".");
Console.WriteLine();
Console.WriteLine($"Using the delimiter string:\n   \"{stringSeparators[0]}\"");
Console.WriteLine();

// Split a string delimited by another string and return all elements.
result = source.Split(stringSeparators, StringSplitOptions.None);
Console.WriteLine($"Result including all elements ({result.Length} elements):");
Console.Write("   ");
foreach (string s in result)
{
    Console.Write("'{0}' ", String.IsNullOrEmpty(s) ? "<>" : s);
}
Console.WriteLine();
Console.WriteLine();

// Split delimited by another string and return all non-empty elements.
result = source.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);
Console.WriteLine($"Result including non-empty elements ({result.Length} elements):");
Console.Write("   ");
foreach (string s in result)
{
    Console.Write("'{0}' ", String.IsNullOrEmpty(s) ? "<>" : s);
}
Console.WriteLine();

// The example displays the following output:
//    Splitting the string:
//       "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".
//    
//    Using the delimiter string:
//       "[stop]"
//    
//    Result including all elements (9 elements):
//       '<>' 'ONE' '<>' 'TWO' '<>' '<>' 'THREE' '<>' '<>'
//    
//    Result including non-empty elements (3 elements):
//       'ONE' 'TWO' 'THREE'
let source = "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]"
let stringSeparators = [| "[stop]" |]

// Display the original string and delimiter string.
printfn $"Splitting the string:\n   \"{source}\".\n"
printfn $"Using the delimiter string:\n   \"{stringSeparators[0]}\"\n"

// Split a string delimited by another string and return all elements.
let result = source.Split(stringSeparators, StringSplitOptions.None)
printfn $"Result including all elements ({result.Length} elements):"
printf "   "
for s in result do
    printf $"""'{if String.IsNullOrEmpty s then "<>" else s}' """
printfn "\n"

// Split delimited by another string and return all non-empty elements.
let result = source.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)
Console.WriteLine($"Result including non-empty elements ({result.Length} elements):")
printf "   "
for s in result do
    printf $"""'{if String.IsNullOrEmpty s then "<>" else s}' """
printfn ""

// The example displays the following output:
//    Splitting the string:
//       "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".
//    
//    Using the delimiter string:
//       "[stop]"
//    
//    let result including all elements (9 elements):
//       '<>' 'ONE' '<>' 'TWO' '<>' '<>' 'THREE' '<>' '<>'
//    
//    let result including non-empty elements (3 elements):
//       'ONE' 'TWO' 'THREE'
Dim source As String = "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]"
Dim stringSeparators() As String = {"[stop]"}
Dim result() As String

' Display the original string and delimiter string.
Console.WriteLine("Splitting the string:{0}   '{1}'.", vbCrLf, source)
Console.WriteLine()
Console.WriteLine("Using the delimiter string:{0}   '{1}'.",
                vbCrLf, stringSeparators(0))
Console.WriteLine()

' Split a string delimited by another string and return all elements.
result = source.Split(stringSeparators, StringSplitOptions.None)
Console.WriteLine("Result including all elements ({0} elements):",
                result.Length)
Console.Write("   ")
For Each s As String In result
    Console.Write("'{0}' ", IIf(String.IsNullOrEmpty(s), "<>", s))
Next
Console.WriteLine()
Console.WriteLine()

' Split delimited by another string and return all non-empty elements.
result = source.Split(stringSeparators,
                    StringSplitOptions.RemoveEmptyEntries)
Console.WriteLine("Result including non-empty elements ({0} elements):",
                result.Length)
Console.Write("   ")
For Each s As String In result
    Console.Write("'{0}' ", IIf(String.IsNullOrEmpty(s), "<>", s))
Next
Console.WriteLine()

' The example displays the following output:
'    Splitting the string:
'       "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".
'    
'    Using the delimiter string:
'       "[stop]"
'    
'    Result including all elements (9 elements):
'       '<>' 'ONE' '<>' 'TWO' '<>' '<>' 'THREE' '<>' '<>'
'    
'    Result including non-empty elements (3 elements):
'       'ONE' 'TWO' 'THREE'

次の例では、区切り記号と空白文字を含む区切り記号の配列を定義します。 この配列を の値 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

メソッドは、 引数を に設定して options 呼び出されることに注意してください StringSplitOptions.RemoveEmptyEntries。 これにより、返される配列に、句読点と空白文字の間の空の部分文字列の一致を表す値を含 String.Empty めなくなります。

注釈

文字列が既知の文字列セットで区切られている場合は、 メソッドを Split 使用して部分文字列に区切ることができます。

区切り記号文字列は、返される配列の要素には含まれません。 たとえば、配列に separator 文字列 "--" が含まれており、現在の文字列インスタンスの値が "aa--bb--cc" の場合、メソッドは"aa"、"bb"、"cc" の 3 つの要素を含む配列を返します。

このインスタンスに の文字列 separatorが含まれていない場合、返される配列は、このインスタンスを含む 1 つの要素で構成されます。

パラメーターが optionsRemoveEmptyEntries 、このインスタンスの長さが 0 の場合、メソッドは空の配列を返します。

separator 各要素は、1 つ以上の文字で構成される個別の区切り記号を定義します。 引数が optionsNone、2 つの区切り記号が隣接している場合、またはこのインスタンスの先頭または末尾に区切り記号が見つかった場合、対応する配列要素には が含まれます String.Empty。 たとえば、"-" と "_" の 2 つの要素が含まれている場合separator、文字列インスタンスの値は "-_aa-_" で、引数の値は です。このメソッドはNone、次の options 5 つの要素を持つ文字列配列を返します。

  1. String.Emptyは、インデックス 0 の "-" 部分文字列の前にある空の文字列を表します。

  2. String.Emptyは、インデックス 0 の "-" 部分文字列とインデックス 1 の "_" 部分文字列の間の空の文字列を表します。

  3. "aa"

  4. String.Emptyは、インデックス 4 の "-" 部分文字列に続く空の文字列を表します。

  5. String.Emptyは、インデックス 5 の "_" 部分文字列に続く空の文字列を表します。

区切り記号配列

内のいずれかの要素が複数の文字で separator 構成されている場合、部分文字列全体は区切り記号と見なされます。 たとえば、 の要素 separator の 1 つが "10" の場合、文字列 "This10is10a10string" を分割しようとすると、次の 4 要素配列 {"This"、"is"、"a"、"string." }が返されます。

パラメーターが separator または null に空でない文字列が含まれない場合は、空白文字が区切り記号であると見なされます。 空白文字は Unicode 標準によって定義され、 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 、 パラメーター内の 1 つ以上の文字列で区切られたこの文字列内の部分文字列を separator 抽出し、それらの部分文字列を配列の要素として返します。

メソッドは Split 、大文字と小文字を区別する序数の並べ替え規則を使用して比較を実行することで、区切り記号を検索します。 単語、文字列、および序数の並べ替えの詳細については、 列挙を System.Globalization.CompareOptions 参照してください。

メソッドはSplit、 の値が null または空のseparator文字列 ("") の要素を無視します。

内の separator 文字列に共通の文字がある場合にあいまいな結果を回避するために、 Split 操作はインスタンスの値の先頭から末尾に進み、インスタンス内の区切り記号と等しい 内の separator 最初の要素と一致します。 インスタンスで部分文字列が検出される順序は、 内の要素 separatorの順序よりも優先されます。

たとえば、値が "abcdef" のインスタンスがあるとします。 の最初の separator 要素が "ef" で、2 番目の要素が "bcde" の場合、分割操作の結果は、"a" と "f" の 2 つの要素を含む文字列配列になります。 これは、インスタンス "bcde" の部分文字列が検出され、部分文字列 "f" が検出される前に の separator 要素と一致するためです。

ただし、 の最初の separator 要素が "bcd" で、2 番目の要素が "bc" の場合、分割操作の結果は、"a" と "ef" の 2 つの要素を含む文字列配列になります。 これは、"bcd" が インスタンスの区切り記号と separator 一致する の最初の区切り記号であるためです。 区切り記号の順序が逆になっているため、最初の要素が "bc" で、2 番目の要素が "bcd" の場合、結果は "a" と "def" の 2 つの要素を含む文字列配列になります。

パフォーマンスに関する考慮事項

メソッドは Split 、返された配列オブジェクトにメモリを割り当て、各配列要素に String オブジェクトを割り当てます。 アプリケーションで最適なパフォーマンスが必要な場合、またはアプリケーションでメモリ割り当ての管理が重要な場合は、 メソッドまたは IndexOfAny メソッドを使用し、必要に応じて メソッドをCompare使用IndexOfして文字列内の部分文字列を検索することを検討してください。

区切り文字で文字列を分割する場合は、 メソッドまたは IndexOfAny メソッドをIndexOf使用して、文字列内の区切り文字を見つけます。 区切り文字列で文字列を分割する場合は、 メソッドまたは IndexOfAny メソッドをIndexOf使用して、区切り文字列の最初の文字を見つけます。 次に、 メソッドを Compare 使用して、最初の文字の後の文字が区切り文字の残りの文字と等しいかどうかを判断します。

さらに、同じ文字セットを使用して複数 Split のメソッド呼び出しで文字列を分割する場合は、1 つの配列を作成し、各メソッド呼び出しでそれを参照することを検討してください。 これにより、各メソッド呼び出しの追加オーバーヘッドが大幅に削減されます。

注意 (呼び出し元)

.NET Framework 3.5 以前のバージョンでは、 メソッドに が渡されたnullseparator場合、または文字が含まれていない場合Split(Char[])、メソッドは文字列をトリミングする場合とはTrim(Char[])少し異なる空白文字のセットを使用して文字列を分割します。 .NET Framework 4 以降では、両方のメソッドで同じ Unicode 空白文字のセットが使用されます。

適用対象

Split(Char, Int32, StringSplitOptions)

指定された 1 つの区切り文字およびオプション (任意) に基づいて文字列を最大数の部分文字列に分割します。 指定された文字区切り記号に基づいて文字列を最大数の部分文字列に分割します。オプションで、結果からの空の部分文字列を省略します。

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

部分文字列をトリミングして空の部分文字列を含めるかどうかを指定する列挙値のビットごとの組み合わせ。

戻り値

String[]

separator で区切られた、このインスタンスの最大 count の部分文字列を格納する配列。

注釈

文字列が既に 1 回分割 count されているが、文字列の末尾に達していない場合、返される配列の最後の文字列には、このインスタンスの残りの末尾の部分文字列がそのまま含まれます。

適用対象

Split(Char[], Int32, StringSplitOptions)

指定された区切り文字およびオプション (任意) に基づいて文字列を最大数の部分文字列に分割します。

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

部分文字列をトリミングして空の部分文字列を含めるかどうかを指定する列挙値のビットごとの組み合わせ。

戻り値

String[]

この文字列を、separator のいずれかまたは複数の文字で区切ることによって取り出された部分文字列を格納する配列。 詳細については、「解説」を参照してください。

属性

例外

count が負の値です。

optionsStringSplitOptions 値のいずれでもありません。

次の例では、 列挙を 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.
string s1 = ",ONE,,TWO,,,THREE,,";
string s2 = "[stop]" +
            "ONE[stop][stop]" +
            "TWO[stop][stop][stop]" +
            "THREE[stop][stop]";
char[] charSeparators = new char[] { ',' };
string[] stringSeparators = new string[] { "[stop]" };
string[] result;
// ------------------------------------------------------------------------------
// Split a string delimited by characters.
// ------------------------------------------------------------------------------
Console.WriteLine("1) Split a string delimited by characters:\n");

// Display the original string and delimiter characters.
Console.WriteLine($"1a) The original string is \"{s1}\".");
Console.WriteLine($"The delimiter character is '{charSeparators[0]}'.\n");

// Split a string delimited by characters and return all elements.
Console.WriteLine("1b) Split a string delimited by characters and " +
                  "return all elements:");
result = s1.Split(charSeparators, StringSplitOptions.None);
Show(result);

// Split a string delimited by characters and return all non-empty elements.
Console.WriteLine("1c) Split a string delimited by characters and " +
                  "return all non-empty elements:");
result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);
Show(result);

// Split the original string into the string and empty string before the
// delimiter and the remainder of the original string after the delimiter.
Console.WriteLine("1d) Split a string delimited by characters and " +
                  "return 2 elements:");
result = s1.Split(charSeparators, 2, StringSplitOptions.None);
Show(result);

// Split the original string into the string after the delimiter and the
// remainder of the original string after the delimiter.
Console.WriteLine("1e) Split a string delimited by characters and " +
                  "return 2 non-empty elements:");
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries);
Show(result);

// ------------------------------------------------------------------------------
// Split a string delimited by another string.
// ------------------------------------------------------------------------------
Console.WriteLine("2) Split a string delimited by another string:\n");

// Display the original string and delimiter string.
Console.WriteLine($"2a) The original string is \"{s2}\".");
Console.WriteLine($"The delimiter string is \"{stringSeparators[0]}\".\n");

// Split a string delimited by another string and return all elements.
Console.WriteLine("2b) Split a string delimited by another string and " +
                  "return all elements:");
result = s2.Split(stringSeparators, StringSplitOptions.None);
Show(result);

// Split the original string at the delimiter and return all non-empty elements.
Console.WriteLine("2c) Split a string delimited by another string and " +
                  "return all non-empty elements:");
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);
Show(result);

// Split the original string into the empty string before the
// delimiter and the remainder of the original string after the delimiter.
Console.WriteLine("2d) Split a string delimited by another string and " +
                  "return 2 elements:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.None);
Show(result);

// Split the original string into the string after the delimiter and the
// remainder of the original string after the delimiter.
Console.WriteLine("2e) Split a string delimited by another string and " +
                  "return 2 non-empty elements:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries);
Show(result);

// Display the array of separated strings using a local function
void Show(string[] entries)
{
    Console.WriteLine($"The return value contains these {entries.Length} elements:");
    foreach (string entry in entries)
    {
        Console.Write($"<{entry}>");
    }
    Console.Write("\n\n");
}

/*
This example produces the following results:

1) Split a string delimited by characters:

1a) The original string is ",ONE,,TWO,,,THREE,,".
The delimiter character is ','.

1b) Split a string delimited by characters and return all elements:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>

1c) Split a string delimited by characters and return all non-empty elements:
The return value contains these 3 elements:
<ONE><TWO><THREE>

1d) Split a string delimited by characters and return 2 elements:
The return value contains these 2 elements:
<><ONE,,TWO,,,THREE,,>

1e) Split a string delimited by characters and return 2 non-empty elements:
The return value contains these 2 elements:
<ONE><TWO,,,THREE,,>

2) Split a string delimited by another string:

2a) The original string is "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".
The delimiter string is "[stop]".

2b) Split a string delimited by another string and return all elements:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>

2c) Split a string delimited by another string and return all non-empty elements:
The return value contains these 3 elements:
<ONE><TWO><THREE>

2d) Split a string delimited by another string and return 2 elements:
The return value contains these 2 elements:
<><ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]>

2e) Split a string delimited by another string and return 2 non-empty elements:
The return value contains these 2 elements:
<ONE><TWO[stop][stop][stop]THREE[stop][stop]>

*/
// This example demonstrates the String.Split() methods that use
// the StringSplitOptions enumeration.
 
// Display the array of separated strings using a local function
let show  (entries: string[]) =
    printfn $"The return value contains these {entries.Length} elements:"
    for entry in entries do
        printf $"<{entry}>"
    printf "\n\n"

let s1 = ",ONE,,TWO,,,THREE,,"
let s2 = "[stop]" +
         "ONE[stop][stop]" +
         "TWO[stop][stop][stop]" +
         "THREE[stop][stop]"
let charSeparators = [| ',' |]
let stringSeparators = [| "[stop]" |]
// ------------------------------------------------------------------------------
// Split a string delimited by characters.
// ------------------------------------------------------------------------------
printfn "1) Split a string delimited by characters:\n"

// Display the original string and delimiter characters.
printfn $"1a) The original string is \"{s1}\"."
printfn $"The delimiter character is '{charSeparators[0]}'.\n"

// Split a string delimited by characters and return all elements.
printfn "1b) Split a string delimited by characters and return all elements:"
let result = s1.Split(charSeparators, StringSplitOptions.None)
show result

// Split a string delimited by characters and return all non-empty elements.
printfn "1c) Split a string delimited by characters and return all non-empty elements:"
let result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries)
show result

// Split the original string into the string and empty string before the
// delimiter and the remainder of the original string after the delimiter.
printfn "1d) Split a string delimited by characters and return 2 elements:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.None)
show result

// Split the original string into the string after the delimiter and the
// remainder of the original string after the delimiter.
printfn "1e) Split a string delimited by characters and return 2 non-empty elements:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
show result

// ------------------------------------------------------------------------------
// Split a string delimited by another string.
// ------------------------------------------------------------------------------
printfn "2) Split a string delimited by another string:\n"

// Display the original string and delimiter string.
printfn $"2a) The original string is \"{s2}\"."
printfn $"The delimiter string is \"{stringSeparators[0]}\".\n"

// Split a string delimited by another string and return all elements.
printfn "2b) Split a string delimited by another string and return all elements:"
let result = s2.Split(stringSeparators, StringSplitOptions.None)
show result

// Split the original string at the delimiter and return all non-empty elements.
printfn "2c) Split a string delimited by another string and return all non-empty elements:"
let result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)
show result

// Split the original string into the empty string before the
// delimiter and the remainder of the original string after the delimiter.
printfn "2d) Split a string delimited by another string and return 2 elements:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.None)
show result

// Split the original string into the string after the delimiter and the
// remainder of the original string after the delimiter.
printfn "2e) Split a string delimited by another string and return 2 non-empty elements:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
show result

(*
This example produces the following results:

1) Split a string delimited by characters:

1a) The original string is ",ONE,,TWO,,,THREE,,".
The delimiter character is ','.

1b) Split a string delimited by characters and return all elements:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>

1c) Split a string delimited by characters and return all non-empty elements:
The return value contains these 3 elements:
<ONE><TWO><THREE>

1d) Split a string delimited by characters and return 2 elements:
The return value contains these 2 elements:
<><ONE,,TWO,,,THREE,,>

1e) Split a string delimited by characters and return 2 non-empty elements:
The return value contains these 2 elements:
<ONE><TWO,,,THREE,,>

2) Split a string delimited by another string:

2a) The original string is "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".
The delimiter string is "[stop]".

2b) Split a string delimited by another string and return all elements:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>

2c) Split a string delimited by another string and return all non-empty elements:
The return value contains these 3 elements:
<ONE><TWO><THREE>

2d) Split a string delimited by another string and return 2 elements:
The return value contains these 2 elements:
<><ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]>

2e) Split a string delimited by another string and return 2 non-empty elements:
The return value contains these 2 elements:
<ONE><TWO[stop][stop][stop]THREE[stop][stop]>

*)
    Dim s1 As String = ",ONE,,TWO,,,THREE,,"
    Dim s2 As String = "[stop]" &
                       "ONE[stop][stop]" &
                       "TWO[stop][stop][stop]" &
                       "THREE[stop][stop]"
    Dim charSeparators() As Char = {","c}
    Dim stringSeparators() As String = {"[stop]"}
    Dim result() As String
    ' ------------------------------------------------------------------------------
    ' Split a string delimited by characters.
    ' ------------------------------------------------------------------------------
    Console.WriteLine("1) Split a string delimited by characters:" & vbCrLf)

    ' Display the original string and delimiter characters.
    Console.WriteLine("1a) The original string is ""{0}"".", s1)
    Console.WriteLine("The delimiter character is '{0}'." & vbCrLf, charSeparators(0))

    ' Split a string delimited by characters and return all elements.
    Console.WriteLine("1b) Split a string delimited by characters and " &
                      "return all elements:")
    result = s1.Split(charSeparators, StringSplitOptions.None)
    Show(result)

    ' Split a string delimited by characters and return all non-empty elements.
    Console.WriteLine("1c) Split a string delimited by characters and " &
                      "return all non-empty elements:")
    result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries)
    Show(result)

    ' Split the original string into the string and empty string before the 
    ' delimiter and the remainder of the original string after the delimiter.
    Console.WriteLine("1d) Split a string delimited by characters and " &
                      "return 2 elements:")
    result = s1.Split(charSeparators, 2, StringSplitOptions.None)
    Show(result)

    ' Split the original string into the string after the delimiter and the 
    ' remainder of the original string after the delimiter.
    Console.WriteLine("1e) Split a string delimited by characters and " &
                      "return 2 non-empty elements:")
    result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
    Show(result)

    ' ------------------------------------------------------------------------------
    ' Split a string delimited by another string.
    ' ------------------------------------------------------------------------------
    Console.WriteLine("2) Split a string delimited by another string:" & vbCrLf)

    ' Display the original string and delimiter string.
    Console.WriteLine("2a) The original string is ""{0}"".", s2)
    Console.WriteLine("The delimiter string is ""{0}""." & vbCrLf, stringSeparators(0))

    ' Split a string delimited by another string and return all elements.
    Console.WriteLine("2b) Split a string delimited by another string and " &
                      "return all elements:")
    result = s2.Split(stringSeparators, StringSplitOptions.None)
    Show(result)

    ' Split the original string at the delimiter and return all non-empty elements.
    Console.WriteLine("2c) Split a string delimited by another string and " &
                      "return all non-empty elements:")
    result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)
    Show(result)

    ' Split the original string into the empty string before the 
    ' delimiter and the remainder of the original string after the delimiter.
    Console.WriteLine("2d) Split a string delimited by another string and " &
                      "return 2 elements:")
    result = s2.Split(stringSeparators, 2, StringSplitOptions.None)
    Show(result)

    ' Split the original string into the string after the delimiter and the 
    ' remainder of the original string after the delimiter.
    Console.WriteLine("2e) Split a string delimited by another string and " &
                      "return 2 non-empty elements:")
    result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
    Show(result)

End Sub


' Display the array of separated strings.
Public Shared Sub Show(ByVal entries() As String)
    Console.WriteLine("The return value contains these {0} elements:", entries.Length)
    Dim entry As String
    For Each entry In entries
        Console.Write("<{0}>", entry)
    Next entry
    Console.Write(vbCrLf & vbCrLf)

End Sub

'This example produces the following results:
'
'1) Split a string delimited by characters:
'
'1a) The original string is ",ONE,,TWO,,,THREE,,".
'The delimiter character is ','.
'
'1b) Split a string delimited by characters and return all elements:
'The return value contains these 9 elements:
'<><ONE><><TWO><><><THREE><><>
'
'1c) Split a string delimited by characters and return all non-empty elements:
'The return value contains these 3 elements:
'<ONE><TWO><THREE>
'
'1d) Split a string delimited by characters and return 2 elements:
'The return value contains these 2 elements:
'<><ONE,,TWO,,,THREE,,>
'
'1e) Split a string delimited by characters and return 2 non-empty elements:
'The return value contains these 2 elements:
'<ONE><TWO,,,THREE,,>
'
'2) Split a string delimited by another string:
'
'2a) The original string is "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".
'The delimiter string is "[stop]".
'
'2b) Split a string delimited by another string and return all elements:
'The return value contains these 9 elements:
'<><ONE><><TWO><><><THREE><><>
'
'2c) Split a string delimited by another string and return all non-empty elements:
'The return value contains these 3 elements:
'<ONE><TWO><THREE>
'
'2d) Split a string delimited by another string and return 2 elements:
'The return value contains these 2 elements:
'<><ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]>
'
'2e) Split a string delimited by another string and return 2 non-empty elements:
'The return value contains these 2 elements:
'<ONE><TWO[stop][stop][stop]THREE[stop][stop]>
'

注釈

区切り文字は、返される配列の要素には含まれません。

このインスタンスに の文字 separatorが含まれていない場合、または count パラメーターが 1 の場合、返される配列は、このインスタンスを含む 1 つの要素で構成されます。

パラメーターが separator または null に文字を含まない場合、空白文字は区切り記号と見なされます。 空白文字は Unicode 標準によって定義され、 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 、このインスタンスの長さが 0 の場合は、空の配列が返されます。

separator 各要素は、個別の区切り文字を定義します。 パラメーターが optionsNone、2 つの区切り記号が隣接している場合、またはこのインスタンスの先頭または末尾に区切り記号が見つかった場合、対応する配列要素には が含まれます Empty

このインスタンスに複数countの部分文字列がある場合は、戻り値の最初の要素から 1 を引いた要素で最初countcountのマイナス 1 部分文字列が返され、このインスタンスの残りの文字は戻り値の最後の要素で返されます。

が部分文字列の数より大きい場合 count は、使用可能な部分文字列が返され、例外はスローされません。

パフォーマンスに関する考慮事項

メソッドは Split 、返された配列オブジェクトにメモリを割り当て、各配列要素に String オブジェクトを割り当てます。 アプリケーションで最適なパフォーマンスが必要な場合、またはアプリケーションでメモリ割り当ての管理が重要な場合は、 メソッドまたは IndexOfAny メソッドを使用し、必要に応じて メソッドをCompare使用IndexOfして文字列内の部分文字列を検索することを検討してください。

区切り文字で文字列を分割する場合は、 メソッドまたは IndexOfAny メソッドをIndexOf使用して、文字列内の区切り文字を見つけます。 区切り文字列で文字列を分割する場合は、 メソッドまたは IndexOfAny メソッドをIndexOf使用して、区切り文字列の最初の文字を見つけます。 次に、 メソッドを Compare 使用して、最初の文字の後の文字が区切り文字の残りの文字と等しいかどうかを判断します。

さらに、同じ文字セットを使用して複数 Split のメソッド呼び出しで文字列を分割する場合は、1 つの配列を作成し、各メソッド呼び出しでそれを参照することを検討してください。 これにより、各メソッド呼び出しの追加オーバーヘッドが大幅に削減されます。

注意 (呼び出し元)

.NET Framework 3.5 以前のバージョンでは、 メソッドに が渡されたnullseparator場合、または文字が含まれていない場合Split(Char[])、メソッドは文字列をトリミングする場合とはTrim(Char[])少し異なる空白文字のセットを使用して文字列を分割します。 .NET Framework 4 以降では、両方のメソッドで同じ Unicode 空白文字のセットが使用されます。

適用対象

Split(String, Int32, StringSplitOptions)

指定された 1 つの区切り文字列およびオプション (任意) に基づいて文字列を最大数の部分文字列に分割します。

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

部分文字列をトリミングして空の部分文字列を含めるかどうかを指定する列挙値のビットごとの組み合わせ。

戻り値

String[]

separator で区切られた、このインスタンスの最大 count の部分文字列を格納する配列。

注釈

文字列が既に 1 回分割 count されているが、文字列の末尾に達していない場合、返される配列の最後の文字列には、このインスタンスの残りの末尾の部分文字列がそのまま含まれます。

適用対象

Split(String[], Int32, StringSplitOptions)

指定された区切り文字列およびオプション (任意) に基づいて文字列を最大数の部分文字列に分割します。

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

部分文字列をトリミングして空の部分文字列を含めるかどうかを指定する列挙値のビットごとの組み合わせ。

戻り値

String[]

この文字列を、separator 配列のいずれかまたは複数の要素 (文字列) で区切ることによって取り出された部分文字列を格納する配列。 詳細については、「解説」を参照してください。

属性

例外

count が負の値です。

optionsStringSplitOptions 値のいずれでもありません。

次の例では、 列挙を 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.
string s1 = ",ONE,,TWO,,,THREE,,";
string s2 = "[stop]" +
            "ONE[stop][stop]" +
            "TWO[stop][stop][stop]" +
            "THREE[stop][stop]";
char[] charSeparators = new char[] { ',' };
string[] stringSeparators = new string[] { "[stop]" };
string[] result;
// ------------------------------------------------------------------------------
// Split a string delimited by characters.
// ------------------------------------------------------------------------------
Console.WriteLine("1) Split a string delimited by characters:\n");

// Display the original string and delimiter characters.
Console.WriteLine($"1a) The original string is \"{s1}\".");
Console.WriteLine($"The delimiter character is '{charSeparators[0]}'.\n");

// Split a string delimited by characters and return all elements.
Console.WriteLine("1b) Split a string delimited by characters and " +
                  "return all elements:");
result = s1.Split(charSeparators, StringSplitOptions.None);
Show(result);

// Split a string delimited by characters and return all non-empty elements.
Console.WriteLine("1c) Split a string delimited by characters and " +
                  "return all non-empty elements:");
result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);
Show(result);

// Split the original string into the string and empty string before the
// delimiter and the remainder of the original string after the delimiter.
Console.WriteLine("1d) Split a string delimited by characters and " +
                  "return 2 elements:");
result = s1.Split(charSeparators, 2, StringSplitOptions.None);
Show(result);

// Split the original string into the string after the delimiter and the
// remainder of the original string after the delimiter.
Console.WriteLine("1e) Split a string delimited by characters and " +
                  "return 2 non-empty elements:");
result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries);
Show(result);

// ------------------------------------------------------------------------------
// Split a string delimited by another string.
// ------------------------------------------------------------------------------
Console.WriteLine("2) Split a string delimited by another string:\n");

// Display the original string and delimiter string.
Console.WriteLine($"2a) The original string is \"{s2}\".");
Console.WriteLine($"The delimiter string is \"{stringSeparators[0]}\".\n");

// Split a string delimited by another string and return all elements.
Console.WriteLine("2b) Split a string delimited by another string and " +
                  "return all elements:");
result = s2.Split(stringSeparators, StringSplitOptions.None);
Show(result);

// Split the original string at the delimiter and return all non-empty elements.
Console.WriteLine("2c) Split a string delimited by another string and " +
                  "return all non-empty elements:");
result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);
Show(result);

// Split the original string into the empty string before the
// delimiter and the remainder of the original string after the delimiter.
Console.WriteLine("2d) Split a string delimited by another string and " +
                  "return 2 elements:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.None);
Show(result);

// Split the original string into the string after the delimiter and the
// remainder of the original string after the delimiter.
Console.WriteLine("2e) Split a string delimited by another string and " +
                  "return 2 non-empty elements:");
result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries);
Show(result);

// Display the array of separated strings using a local function
void Show(string[] entries)
{
    Console.WriteLine($"The return value contains these {entries.Length} elements:");
    foreach (string entry in entries)
    {
        Console.Write($"<{entry}>");
    }
    Console.Write("\n\n");
}

/*
This example produces the following results:

1) Split a string delimited by characters:

1a) The original string is ",ONE,,TWO,,,THREE,,".
The delimiter character is ','.

1b) Split a string delimited by characters and return all elements:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>

1c) Split a string delimited by characters and return all non-empty elements:
The return value contains these 3 elements:
<ONE><TWO><THREE>

1d) Split a string delimited by characters and return 2 elements:
The return value contains these 2 elements:
<><ONE,,TWO,,,THREE,,>

1e) Split a string delimited by characters and return 2 non-empty elements:
The return value contains these 2 elements:
<ONE><TWO,,,THREE,,>

2) Split a string delimited by another string:

2a) The original string is "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".
The delimiter string is "[stop]".

2b) Split a string delimited by another string and return all elements:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>

2c) Split a string delimited by another string and return all non-empty elements:
The return value contains these 3 elements:
<ONE><TWO><THREE>

2d) Split a string delimited by another string and return 2 elements:
The return value contains these 2 elements:
<><ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]>

2e) Split a string delimited by another string and return 2 non-empty elements:
The return value contains these 2 elements:
<ONE><TWO[stop][stop][stop]THREE[stop][stop]>

*/
// This example demonstrates the String.Split() methods that use
// the StringSplitOptions enumeration.
 
// Display the array of separated strings using a local function
let show  (entries: string[]) =
    printfn $"The return value contains these {entries.Length} elements:"
    for entry in entries do
        printf $"<{entry}>"
    printf "\n\n"

let s1 = ",ONE,,TWO,,,THREE,,"
let s2 = "[stop]" +
         "ONE[stop][stop]" +
         "TWO[stop][stop][stop]" +
         "THREE[stop][stop]"
let charSeparators = [| ',' |]
let stringSeparators = [| "[stop]" |]
// ------------------------------------------------------------------------------
// Split a string delimited by characters.
// ------------------------------------------------------------------------------
printfn "1) Split a string delimited by characters:\n"

// Display the original string and delimiter characters.
printfn $"1a) The original string is \"{s1}\"."
printfn $"The delimiter character is '{charSeparators[0]}'.\n"

// Split a string delimited by characters and return all elements.
printfn "1b) Split a string delimited by characters and return all elements:"
let result = s1.Split(charSeparators, StringSplitOptions.None)
show result

// Split a string delimited by characters and return all non-empty elements.
printfn "1c) Split a string delimited by characters and return all non-empty elements:"
let result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries)
show result

// Split the original string into the string and empty string before the
// delimiter and the remainder of the original string after the delimiter.
printfn "1d) Split a string delimited by characters and return 2 elements:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.None)
show result

// Split the original string into the string after the delimiter and the
// remainder of the original string after the delimiter.
printfn "1e) Split a string delimited by characters and return 2 non-empty elements:"
let result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
show result

// ------------------------------------------------------------------------------
// Split a string delimited by another string.
// ------------------------------------------------------------------------------
printfn "2) Split a string delimited by another string:\n"

// Display the original string and delimiter string.
printfn $"2a) The original string is \"{s2}\"."
printfn $"The delimiter string is \"{stringSeparators[0]}\".\n"

// Split a string delimited by another string and return all elements.
printfn "2b) Split a string delimited by another string and return all elements:"
let result = s2.Split(stringSeparators, StringSplitOptions.None)
show result

// Split the original string at the delimiter and return all non-empty elements.
printfn "2c) Split a string delimited by another string and return all non-empty elements:"
let result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)
show result

// Split the original string into the empty string before the
// delimiter and the remainder of the original string after the delimiter.
printfn "2d) Split a string delimited by another string and return 2 elements:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.None)
show result

// Split the original string into the string after the delimiter and the
// remainder of the original string after the delimiter.
printfn "2e) Split a string delimited by another string and return 2 non-empty elements:"
let result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
show result

(*
This example produces the following results:

1) Split a string delimited by characters:

1a) The original string is ",ONE,,TWO,,,THREE,,".
The delimiter character is ','.

1b) Split a string delimited by characters and return all elements:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>

1c) Split a string delimited by characters and return all non-empty elements:
The return value contains these 3 elements:
<ONE><TWO><THREE>

1d) Split a string delimited by characters and return 2 elements:
The return value contains these 2 elements:
<><ONE,,TWO,,,THREE,,>

1e) Split a string delimited by characters and return 2 non-empty elements:
The return value contains these 2 elements:
<ONE><TWO,,,THREE,,>

2) Split a string delimited by another string:

2a) The original string is "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".
The delimiter string is "[stop]".

2b) Split a string delimited by another string and return all elements:
The return value contains these 9 elements:
<><ONE><><TWO><><><THREE><><>

2c) Split a string delimited by another string and return all non-empty elements:
The return value contains these 3 elements:
<ONE><TWO><THREE>

2d) Split a string delimited by another string and return 2 elements:
The return value contains these 2 elements:
<><ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]>

2e) Split a string delimited by another string and return 2 non-empty elements:
The return value contains these 2 elements:
<ONE><TWO[stop][stop][stop]THREE[stop][stop]>

*)
    Dim s1 As String = ",ONE,,TWO,,,THREE,,"
    Dim s2 As String = "[stop]" &
                       "ONE[stop][stop]" &
                       "TWO[stop][stop][stop]" &
                       "THREE[stop][stop]"
    Dim charSeparators() As Char = {","c}
    Dim stringSeparators() As String = {"[stop]"}
    Dim result() As String
    ' ------------------------------------------------------------------------------
    ' Split a string delimited by characters.
    ' ------------------------------------------------------------------------------
    Console.WriteLine("1) Split a string delimited by characters:" & vbCrLf)

    ' Display the original string and delimiter characters.
    Console.WriteLine("1a) The original string is ""{0}"".", s1)
    Console.WriteLine("The delimiter character is '{0}'." & vbCrLf, charSeparators(0))

    ' Split a string delimited by characters and return all elements.
    Console.WriteLine("1b) Split a string delimited by characters and " &
                      "return all elements:")
    result = s1.Split(charSeparators, StringSplitOptions.None)
    Show(result)

    ' Split a string delimited by characters and return all non-empty elements.
    Console.WriteLine("1c) Split a string delimited by characters and " &
                      "return all non-empty elements:")
    result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries)
    Show(result)

    ' Split the original string into the string and empty string before the 
    ' delimiter and the remainder of the original string after the delimiter.
    Console.WriteLine("1d) Split a string delimited by characters and " &
                      "return 2 elements:")
    result = s1.Split(charSeparators, 2, StringSplitOptions.None)
    Show(result)

    ' Split the original string into the string after the delimiter and the 
    ' remainder of the original string after the delimiter.
    Console.WriteLine("1e) Split a string delimited by characters and " &
                      "return 2 non-empty elements:")
    result = s1.Split(charSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
    Show(result)

    ' ------------------------------------------------------------------------------
    ' Split a string delimited by another string.
    ' ------------------------------------------------------------------------------
    Console.WriteLine("2) Split a string delimited by another string:" & vbCrLf)

    ' Display the original string and delimiter string.
    Console.WriteLine("2a) The original string is ""{0}"".", s2)
    Console.WriteLine("The delimiter string is ""{0}""." & vbCrLf, stringSeparators(0))

    ' Split a string delimited by another string and return all elements.
    Console.WriteLine("2b) Split a string delimited by another string and " &
                      "return all elements:")
    result = s2.Split(stringSeparators, StringSplitOptions.None)
    Show(result)

    ' Split the original string at the delimiter and return all non-empty elements.
    Console.WriteLine("2c) Split a string delimited by another string and " &
                      "return all non-empty elements:")
    result = s2.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)
    Show(result)

    ' Split the original string into the empty string before the 
    ' delimiter and the remainder of the original string after the delimiter.
    Console.WriteLine("2d) Split a string delimited by another string and " &
                      "return 2 elements:")
    result = s2.Split(stringSeparators, 2, StringSplitOptions.None)
    Show(result)

    ' Split the original string into the string after the delimiter and the 
    ' remainder of the original string after the delimiter.
    Console.WriteLine("2e) Split a string delimited by another string and " &
                      "return 2 non-empty elements:")
    result = s2.Split(stringSeparators, 2, StringSplitOptions.RemoveEmptyEntries)
    Show(result)

End Sub


' Display the array of separated strings.
Public Shared Sub Show(ByVal entries() As String)
    Console.WriteLine("The return value contains these {0} elements:", entries.Length)
    Dim entry As String
    For Each entry In entries
        Console.Write("<{0}>", entry)
    Next entry
    Console.Write(vbCrLf & vbCrLf)

End Sub

'This example produces the following results:
'
'1) Split a string delimited by characters:
'
'1a) The original string is ",ONE,,TWO,,,THREE,,".
'The delimiter character is ','.
'
'1b) Split a string delimited by characters and return all elements:
'The return value contains these 9 elements:
'<><ONE><><TWO><><><THREE><><>
'
'1c) Split a string delimited by characters and return all non-empty elements:
'The return value contains these 3 elements:
'<ONE><TWO><THREE>
'
'1d) Split a string delimited by characters and return 2 elements:
'The return value contains these 2 elements:
'<><ONE,,TWO,,,THREE,,>
'
'1e) Split a string delimited by characters and return 2 non-empty elements:
'The return value contains these 2 elements:
'<ONE><TWO,,,THREE,,>
'
'2) Split a string delimited by another string:
'
'2a) The original string is "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]".
'The delimiter string is "[stop]".
'
'2b) Split a string delimited by another string and return all elements:
'The return value contains these 9 elements:
'<><ONE><><TWO><><><THREE><><>
'
'2c) Split a string delimited by another string and return all non-empty elements:
'The return value contains these 3 elements:
'<ONE><TWO><THREE>
'
'2d) Split a string delimited by another string and return 2 elements:
'The return value contains these 2 elements:
'<><ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]>
'
'2e) Split a string delimited by another string and return 2 non-empty elements:
'The return value contains these 2 elements:
'<ONE><TWO[stop][stop][stop]THREE[stop][stop]>
'

注釈

区切り記号文字列は、返される配列の要素には含まれません。

このインスタンスに separatorに文字列が含まれていない場合、または count パラメーターが 1 の場合、返される配列は、このインスタンスを含む 1 つの要素で構成されます。

パラメーターが separator または null に文字を含まない場合、空白文字は区切り記号と見なされます。 空白文字は Unicode 標準によって定義され、 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 、このインスタンスの長さが 0 の場合は、空の配列が返されます。

separator 各要素は、1 つ以上の文字で構成される個別の区切り記号を定義します。 パラメーターが optionsNone、2 つの区切り記号が隣接している場合、またはこのインスタンスの先頭または末尾に区切り記号が見つかった場合、対応する配列要素には が含まれます Empty

このインスタンスに複数countの部分文字列がある場合は、戻り値の最初の要素から 1 を引いた要素で最初countcountのマイナス 1 部分文字列が返され、このインスタンスの残りの文字は戻り値の最後の要素で返されます。

が部分文字列の数より大きい場合 count は、使用可能な部分文字列が返され、例外はスローされません。

区切り記号配列

内のいずれかの要素が複数の文字で separator 構成されている場合、部分文字列全体は区切り記号と見なされます。 たとえば、 の要素 separator の 1 つが "10" の場合、文字列 "This10is10a10string" を分割しようとすると、次の 4 要素配列が返されます。 { "This", "is", "a", "string." }。

比較の詳細

メソッドは Split 、 パラメーター内の 1 つ以上の文字列で区切られたこの文字列内の部分文字列を separator 抽出し、それらの部分文字列を配列の要素として返します。

メソッドは Split 、大文字と小文字を区別する序数の並べ替え規則を使用して比較を実行することで、区切り記号を検索します。 単語、文字列、および序数の並べ替えの詳細については、 列挙を System.Globalization.CompareOptions 参照してください。

メソッドはSplit、 の値が null または空のseparator文字列 ("") の要素を無視します。

内の separator 文字列に共通の文字がある場合にあいまいな結果を回避するために、 Split メソッドはインスタンスの値の先頭から末尾に進み、インスタンス内の区切り記号と等しい 内 separator の最初の要素と一致します。 インスタンスで部分文字列が検出される順序は、 内の要素 separatorの順序よりも優先されます。

たとえば、値が "abcdef" のインスタンスがあるとします。 の最初の separator 要素が "ef" で、2 番目の要素が "bcde" の場合、分割操作の結果は "a" と "f" になります。 これは、インスタンス "bcde" の部分文字列が検出され、部分文字列 "f" が検出される前に の separator 要素と一致するためです。

ただし、 の最初の separator 要素が "bcd" で、2 番目の要素が "bc" の場合、分割操作の結果は "a" と "ef" になります。 これは、"bcd" が インスタンスの区切り記号と separator 一致する の最初の区切り記号であるためです。 区切り記号の順序が逆になっているため、最初の要素が "bc" で、2 番目の要素が "bcd" の場合、結果は "a" と "def" になります。

パフォーマンスに関する考慮事項

メソッドは Split 、返された配列オブジェクトにメモリを割り当て、各配列要素に String オブジェクトを割り当てます。 アプリケーションで最適なパフォーマンスが必要な場合、またはアプリケーションでメモリ割り当ての管理が重要な場合は、 メソッドまたは IndexOfAny メソッドを使用し、必要に応じて メソッドをCompare使用IndexOfして文字列内の部分文字列を検索することを検討してください。

区切り文字で文字列を分割する場合は、 メソッドまたは IndexOfAny メソッドをIndexOf使用して、文字列内の区切り文字を見つけます。 区切り文字列で文字列を分割する場合は、 メソッドまたは IndexOfAny メソッドをIndexOf使用して、区切り文字列の最初の文字を見つけます。 次に、 メソッドを Compare 使用して、最初の文字の後の文字が区切り文字の残りの文字と等しいかどうかを判断します。

さらに、同じ文字セットを使用して複数 Split のメソッド呼び出しで文字列を分割する場合は、1 つの配列を作成し、各メソッド呼び出しでそれを参照することを検討してください。 これにより、各メソッド呼び出しの追加オーバーヘッドが大幅に削減されます。

注意 (呼び出し元)

.NET Framework 3.5 以前のバージョンでは、 メソッドに が渡されたnullseparator場合、または文字が含まれていない場合Split(Char[])、メソッドは文字列をトリミングする場合とはTrim(Char[])少し異なる空白文字のセットを使用して文字列を分割します。 .NET Framework 4 以降では、両方のメソッドで同じ Unicode 空白文字のセットが使用されます。

適用対象