String.Split メソッド

定義

このインスタンス内の、指定された文字列または Unicode 文字の配列の要素で区切られた部分文字列を格納する文字列配列を返します。Returns a string array that contains the substrings in this instance that are delimited by elements of a specified string or Unicode character array.

オーバーロード

Split(Char[], Int32, StringSplitOptions)

指定された区切り文字およびオプション (任意) に基づいて文字列を最大数の部分文字列に分割します。Splits a string into a maximum number of substrings based on specified delimiting characters and, optionally, options.

Split(Char, Int32, StringSplitOptions)

指定された 1 つの区切り文字およびオプション (任意) に基づいて文字列を最大数の部分文字列に分割します。Splits a string into a maximum number of substrings based on a specified delimiting character and, optionally, options. 指定された文字区切り記号に基づいて文字列を最大数の部分文字列に分割します。オプションで、結果からの空の部分文字列を省略します。Splits a string into a maximum number of substrings based on the provided character separator, optionally omitting empty substrings from the result.

Split(String[], Int32, StringSplitOptions)

指定された区切り文字列およびオプション (任意) に基づいて文字列を最大数の部分文字列に分割します。Splits a string into a maximum number of substrings based on specified delimiting strings and, optionally, options.

Split(String[], StringSplitOptions)

指定された 1 つの区切り文字列およびオプション (任意) に基づいて文字列を部分文字列に分割します。Splits a string into substrings based on a specified delimiting string and, optionally, options.

Split(String, Int32, StringSplitOptions)

指定された 1 つの区切り文字列およびオプション (任意) に基づいて文字列を最大数の部分文字列に分割します。Splits a string into a maximum number of substrings based on a specified delimiting string and, optionally, options.

Split(Char[], StringSplitOptions)

指定された区切り文字およびオプションに基づいて文字列を部分文字列に分割します。Splits a string into substrings based on specified delimiting characters and options.

Split(Char[], Int32)

指定された区切り文字に基づいて文字列を最大数の部分文字列に分割します。Splits a string into a maximum number of substrings based on specified delimiting characters.

Split(Char, StringSplitOptions)

指定された 1 つの区切り文字およびオプション (任意) に基づいて文字列を部分文字列に分割します。Splits a string into substrings based on a specified delimiting character and, optionally, options.

Split(String, StringSplitOptions)

指定された文字列の区切り記号に基づいて文字列を部分文字列に分割します。Splits a string into substrings that are based on the provided string separator.

Split(Char[])

指定された区切り文字に基づいて文字列を部分文字列に分割します。Splits a string into substrings based on specified delimiting characters.

注釈

Split は、区切られた文字列を部分文字列に分割する場合に使用します。Split is used to break a delimited string into substrings. 文字配列または文字列配列を使用して、0個以上の区切り文字または文字列を指定できます。You can use either a character array or a string array to specify zero or more delimiting characters or strings. 区切り文字が指定されていない場合、文字列は空白文字で分割されます。If no delimiting characters are specified, the string is split at white-space characters.

メソッドのオーバーロードを使用すると、メソッド Split (メソッド) によって返される部分文字列の数を制限し、 Split(Char[], Int32) 空の文字列を含めるか、部分文字列を結果に含めるか (メソッド Split(Char[], StringSplitOptions)Split(String[], StringSplitOptions) メソッド)、またはその両方を実行するか (メソッドとメソッド) を指定でき Split(Char[], Int32, StringSplitOptions) Split(String[], Int32, StringSplitOptions) ます。Overloads of the Split method allow you to limit the number of substrings returned by the method (the Split(Char[], Int32) method), to specify whether to include empty strings and/or trim substrings in the result (the Split(Char[], StringSplitOptions) and Split(String[], StringSplitOptions) methods), or to do both (the Split(Char[], Int32, StringSplitOptions) and Split(String[], Int32, StringSplitOptions) methods).

ヒント

Splitメソッドは、区切られた文字列を部分文字列に分割するのに常に最適な方法であるとは限りません。The Split method is not always the best way to break a delimited string into substrings. 区切られた文字列のすべての部分文字列を抽出したくない場合、または区切り記号のセットではなくパターンに基づいて文字列を解析する場合は、正規表現の使用を検討するか、メソッドを使用して文字のインデックスを返す検索メソッドの1つを組み合わせてください SubstringIf you don't want to extract all of the substrings of a delimited string, or if you want to parse a string based on a pattern instead of a set of delimiter characters, consider using regular expressions, or combine one of the search methods that returns the index of a character with the Substring method. 詳細については、「 文字列から部分文字列を抽出する」を参照してください。For more information, see Extract substrings from a string.

Example

次の例では、String.Split() の 3 つの異なるオーバーロードを示します。The following examples show three different overloads of String.Split(). 最初の例では、オーバーロードを呼び出し、 Split(Char[]) 1 つの区切り記号を渡します。The first example calls the Split(Char[]) overload and passes in a single delimiter.

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.
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 つにピリオド文字 (.) が含まれています。As you can see, the period characters (.) are included in two of the substrings. ピリオド文字を除外する場合は、ピリオド文字を追加の区切り文字として追加できます。If you want to exclude the period characters, you can add the period character as an additional delimiting character. その方法を次の例に示します。The next example shows how to do this.

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:
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 つの余分な空の部分文字列が含まれるようになっています。The periods are gone from the substrings, but now two extra empty substrings have been included. これらの空の部分文字列は、単語とそれに続く期間との間の部分文字列を表します。These empty substring represent the substring between a word and the period that follows it. 結果の配列から空の部分文字列を省略するには、Split(Char[], StringSplitOptions) のオーバーロードを呼び出し、options パラメーターとして StringSplitOptions.RemoveEmptyEntries を指定します。To omit empty substrings from the resulting array, you can call the Split(Char[], StringSplitOptions) overload and specify StringSplitOptions.RemoveEmptyEntries for the options parameter.

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
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() さらに例が含まれています。The sections for the individual overloads of String.Split() contain further examples.

Split(Char[], Int32, StringSplitOptions)

指定された区切り文字およびオプション (任意) に基づいて文字列を最大数の部分文字列に分割します。Splits a string into a maximum number of substrings based on specified delimiting characters and, optionally, options.

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[]

この文字列から部分文字列を取り出すために区切り文字として使用する文字の配列、区切り文字が含まれていない空の配列、または nullAn array of characters that delimit the substrings in this string, an empty array that contains no delimiters, or null.

count
Int32

返される最大の部分文字列数。The maximum number of substrings to return.

options
StringSplitOptions

部分文字列をトリミングして空の部分文字列を含めるかどうかを指定する列挙値のビットごとの組み合わせ。A bitwise combination of the enumeration values that specifies whether to trim substrings and include empty substrings.

戻り値

String[]

この文字列を、separator のいずれかまたは複数の文字で区切ることによって取り出された部分文字列を格納する配列。An array that contains the substrings in this string that are delimited by one or more characters in separator. 詳細については、「解説」を参照してください。For more information, see the Remarks section.

属性

例外

count が負の値です。count is negative.

optionsStringSplitOptions 値のいずれでもありません。options is not one of the StringSplitOptions values.

次の例では、 StringSplitOptions 列挙体を使用して、メソッドによって生成される部分文字列を含めたり除外したりし Split ます。The following example uses the StringSplitOptions enumeration to include or exclude substrings generated by the Split method.

// 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]>

*/
    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]>
'

注釈

区切り文字は、返される配列の要素には含まれません。Delimiter characters are not included in the elements of the returned array.

このインスタンスに内の文字が含まれていない場合 separator 、またはパラメーターが1の場合、返される配列は、 count このインスタンスを格納する1つの要素で構成されます。If this instance does not contain any of the characters in separator, or the count parameter is 1, the returned array consists of a single element that contains this instance.

separatorパラメーターがであるか、文字を含んでいない場合は null 、空白文字が区切り記号と見なされます。If the separator parameter is null or contains no characters, white-space characters are assumed to be the delimiters. 空白文字は Unicode 規格によって定義され、 Char.IsWhiteSpace メソッドが true 渡された場合はを返します。White-space characters are defined by the Unicode standard and the Char.IsWhiteSpace method returns true if they are passed to it.

パラメーターにを渡すには null 、の型を指定して、 char[] separator null 他のいくつかのオーバーロード (など) からの呼び出しを明確にする必要があり Split(String[], Int32, StringSplitOptions) ます。To pass null for the char[] separator parameter, you must indicate the type of the null to disambiguate the call from some other overloads, such as Split(String[], Int32, StringSplitOptions). 次の例は、このオーバーロードを明確に識別するいくつかの方法を示しています。The following example shows several ways to unambiguously identify this overload.

string phrase = "The quick  brown fox";

_ = phrase.Split(default(char[]), 3, StringSplitOptions.RemoveEmptyEntries);

_ = phrase.Split((char[])null, 3, StringSplitOptions.RemoveEmptyEntries);

_ = phrase.Split(null as char[], 3, StringSplitOptions.RemoveEmptyEntries);
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パラメーターがゼロの場合、または options パラメーターがで、 RemoveEmptyEntries このインスタンスの長さが0の場合は、空の配列が返されます。If the count parameter is zero, or the options parameter is RemoveEmptyEntries and the length of this instance is zero, an empty array is returned.

の各要素 separator は、個別の区切り文字を定義します。Each element of separator defines a separate delimiter character. optionsパラメーターがであり、2つの区切り記号が隣接している場合 None 、またはこのインスタンスの先頭または末尾に区切り記号がある場合、対応する配列要素にはが含まれ Empty ます。If the options parameter is None, and two delimiters are adjacent or a delimiter is found at the beginning or end of this instance, the corresponding array element contains Empty.

このインスタンスに複数の部分文字列が含まれている場合は、最初の count count -1 の部分文字列が count 戻り値の最初の-1 要素に返され、このインスタンスの残りの文字が戻り値の最後の要素に返されます。If there are more than count substrings in this instance, the first count minus 1 substrings are returned in the first count minus 1 elements of the return value, and the remaining characters in this instance are returned in the last element of the return value.

countが部分文字列の数より大きい場合は、使用可能な部分文字列が返され、例外はスローされません。If count is greater than the number of substrings, the available substrings are returned and no exception is thrown.

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

メソッドは、 Split 返された配列オブジェクトにメモリを割り当て、 String 配列要素ごとにオブジェクトを割り当てます。The Split methods allocate memory for the returned array object and a String object for each array element. アプリケーションで最適なパフォーマンスが求められる場合、またはアプリケーションでメモリ割り当てを管理することが重要な場合は、メソッドまたはメソッドを使用して IndexOf IndexOfAny Compare 文字列内の部分文字列を検索することを検討してください。If your application requires optimal performance or if managing memory allocation is critical in your application, consider using the IndexOf or IndexOfAny method, and optionally the Compare method, to locate a substring within a string.

文字列を区切り文字で分割する場合 IndexOf は、メソッドまたはメソッドを使用し IndexOfAny て、文字列内の区切り記号を検索します。If you are splitting a string at a separator character, use the IndexOf or IndexOfAny method to locate a separator character in the string. 区切り文字列で文字列を分割する場合は、メソッドまたはメソッドを使用して、 IndexOf IndexOfAny 区切り記号文字列の最初の文字を検索します。If you are splitting a string at a separator string, use the IndexOf or IndexOfAny method to locate the first character of the separator string. 次に、メソッドを使用して、 Compare その最初の文字の後の文字が区切り記号文字列の残りの文字と等しいかどうかを確認します。Then use the Compare method to determine whether the characters after that first character are equal to the remaining characters of the separator string.

また、複数のメソッド呼び出しで同じ文字セットを使用して文字列を分割する場合は、 Split 1 つの配列を作成し、各メソッド呼び出しでそれを参照することを検討してください。In addition, if the same set of characters is used to split strings in multiple Split method calls, consider creating a single array and referencing it in each method call. これにより、各メソッド呼び出しのオーバーヘッドが大幅に減少します。This significantly reduces the additional overhead of each method call.

注意 (呼び出し元)

以前のバージョンでは、メソッドに文字が含まれていない、または文字を含んでいないが渡された場合、メソッドは文字列をトリミングするのとは .NET Framework 3.5.NET Framework 3.5 Split(Char[]) 異なり、 separator null 少し異なる空白文字のセットを使用して文字列を分割し Trim(Char[]) ます。In .NET Framework 3.5.NET Framework 3.5 and earlier versions, if the Split(Char[]) method is passed a separator that is null or contains no characters, the method uses a slightly different set of white-space characters to split the string than the Trim(Char[]) method does to trim the string. .NET Framework 4 以降では、どちらのメソッドも、同じ Unicode の空白文字のセットを使用します。Starting with .NET Framework 4, both methods use an identical set of Unicode white-space characters.

適用対象

Split(Char, Int32, StringSplitOptions)

指定された 1 つの区切り文字およびオプション (任意) に基づいて文字列を最大数の部分文字列に分割します。Splits a string into a maximum number of substrings based on a specified delimiting character and, optionally, options. 指定された文字区切り記号に基づいて文字列を最大数の部分文字列に分割します。オプションで、結果からの空の部分文字列を省略します。Splits a string into a maximum number of substrings based on the provided character separator, optionally omitting empty substrings from the result.

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

このインスタンス内の部分文字列を区切る文字。A character that delimits the substrings in this instance.

count
Int32

配列に必要な要素の最大数。The maximum number of elements expected in the array.

options
StringSplitOptions

部分文字列をトリミングして空の部分文字列を含めるかどうかを指定する列挙値のビットごとの組み合わせ。A bitwise combination of the enumeration values that specifies whether to trim substrings and include empty substrings.

戻り値

String[]

separator で区切られた、このインスタンスの最大 count の部分文字列を格納する配列。An array that contains at most count substrings from this instance that are delimited by separator.

注釈

文字列が既に1回分割されていて count も、文字列の末尾に到達していない場合、返された配列の最後の文字列には、このインスタンスの残りの末尾の部分文字列が含まれます。If the string has already been split count - 1 times, but the end of the string has not been reached, then the last string in the returned array will contain this instance's remaining trailing substring, untouched.

適用対象

Split(String[], Int32, StringSplitOptions)

指定された区切り文字列およびオプション (任意) に基づいて文字列を最大数の部分文字列に分割します。Splits a string into a maximum number of substrings based on specified delimiting strings and, optionally, options.

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[]

この文字列から部分文字列を取り出すために区切り文字として使用する文字列、区切り文字が含まれていない空の配列、または nullThe strings that delimit the substrings in this string, an empty array that contains no delimiters, or null.

count
Int32

返される最大の部分文字列数。The maximum number of substrings to return.

options
StringSplitOptions

部分文字列をトリミングして空の部分文字列を含めるかどうかを指定する列挙値のビットごとの組み合わせ。A bitwise combination of the enumeration values that specifies whether to trim substrings and include empty substrings.

戻り値

String[]

この文字列を、separator 配列のいずれかまたは複数の要素 (文字列) で区切ることによって取り出された部分文字列を格納する配列。An array whose elements contain the substrings in this string that are delimited by one or more strings in separator. 詳細については、「解説」を参照してください。For more information, see the Remarks section.

属性

例外

count が負の値です。count is negative.

optionsStringSplitOptions 値のいずれでもありません。options is not one of the StringSplitOptions values.

次の例では、 StringSplitOptions 列挙体を使用して、メソッドによって生成される部分文字列を含めたり除外したりし Split ます。The following example uses the StringSplitOptions enumeration to include or exclude substrings generated by the Split method.

// 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]>

*/
    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]>
'

注釈

区切り記号文字列は、返される配列の要素には含まれません。Delimiter strings are not included in the elements of the returned array.

このインスタンスに内のいずれかの文字列が含まれていない場合、 separator または count パラメーターが1の場合、返される配列は、このインスタンスを格納する1つの要素で構成されます。If this instance does not contain any of the strings in separator, or the count parameter is 1, the returned array consists of a single element that contains this instance.

separatorパラメーターがであるか、文字を含んでいない場合は null 、空白文字が区切り記号と見なされます。If the separator parameter is null or contains no characters, white-space characters are assumed to be the delimiters. 空白文字は Unicode 規格によって定義され、 Char.IsWhiteSpace メソッドが true 渡された場合はを返します。White-space characters are defined by the Unicode standard and the Char.IsWhiteSpace method returns true if they are passed to it.

パラメーターにを渡すには null 、の型を指定して、 string[] separator null 他のいくつかのオーバーロード (など) からの呼び出しを明確にする必要があり Split(Char[], Int32, StringSplitOptions) ます。To pass null for the string[] separator parameter, you must indicate the type of the null to disambiguate the call from some other overloads, such as Split(Char[], Int32, StringSplitOptions). 次の例は、このオーバーロードを明確に識別するいくつかの方法を示しています。The following example shows several ways to unambiguously identify this overload.

string phrase = "The quick  brown fox";

_ = phrase.Split(default(string[]), 3, StringSplitOptions.RemoveEmptyEntries);

_ = phrase.Split((string[])null, 3, StringSplitOptions.RemoveEmptyEntries);

_ = phrase.Split(null as string[], 3, StringSplitOptions.RemoveEmptyEntries);
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パラメーターがゼロの場合、または options パラメーターがで、 RemoveEmptyEntries このインスタンスの長さが0の場合は、空の配列が返されます。If the count parameter is zero, or the options parameter is RemoveEmptyEntries and the length of this instance is zero, an empty array is returned.

の各要素は separator 、1つ以上の文字で構成される個別の区切り記号を定義します。Each element of separator defines a separate delimiter that consists of one or more characters. optionsパラメーターがであり、2つの区切り記号が隣接している場合 None 、またはこのインスタンスの先頭または末尾に区切り記号がある場合、対応する配列要素にはが含まれ Empty ます。If the options parameter is None, and two delimiters are adjacent or a delimiter is found at the beginning or end of this instance, the corresponding array element contains Empty.

このインスタンスに複数の部分文字列が含まれている場合は、最初の count count -1 の部分文字列が count 戻り値の最初の-1 要素に返され、このインスタンスの残りの文字が戻り値の最後の要素に返されます。If there are more than count substrings in this instance, the first count minus 1 substrings are returned in the first count minus 1 elements of the return value, and the remaining characters in this instance are returned in the last element of the return value.

countが部分文字列の数より大きい場合は、使用可能な部分文字列が返され、例外はスローされません。If count is greater than the number of substrings, the available substrings are returned and no exception is thrown.

区切り記号配列The separator array

内のいずれかの要素 separator が複数の文字で構成されている場合、部分文字列全体が区切り記号と見なされます。If any of the elements in separator consists of multiple characters, the entire substring is considered a delimiter. たとえば、内のいずれかの要素 separator が "10" である場合、文字列 "This10is10a10string" を分割しようとしています。For example, if one of the elements in separator is "10", attempting to split the string "This10is10a10string." この4つの要素を持つ配列 {"This"、"is"、"a"、"string" を返します。returns this four-element array: { "This", "is", "a", "string." }.}.

比較の詳細Comparison details

メソッドは、 Split パラメーター内の1つ以上の文字列で区切られたこの文字列の部分文字列を抽出 separator し、それらの部分文字列を配列の要素として返します。The Split method extracts the substrings in this string that are delimited by one or more of the strings in the separator parameter, and returns those substrings as elements of an array.

メソッドは、 Split 大文字と小文字を区別する序数の並べ替え規則を使用して比較を実行することで、区切り記号を検索します。The Split method looks for delimiters by performing comparisons using case-sensitive ordinal sort rules. 単語、文字列、および序数の並べ替えの詳細については、列挙体を参照してください System.Globalization.CompareOptionsFor more information about word, string, and ordinal sorts, see the System.Globalization.CompareOptions enumeration.

メソッドは、 Split separator 値が null または空の文字列 ("") であるの要素を無視します。The Split method ignores any element of separator whose value is null or the empty string ("").

の文字列に共通の文字が含まれている場合にあいまいな結果を避けるために、 separator Split メソッドはインスタンスの値の先頭から末尾まで処理を進め、インスタンス内の区切り記号と等しいの最初の要素と一致し separator ます。To avoid ambiguous results when strings in separator have characters in common, the Split method proceeds from the beginning to the end of the value of the instance, and matches the first element in separator that is equal to a delimiter in the instance. インスタンスでの部分文字列の出現順序は、の要素の順序よりも優先され separator ます。The order in which substrings are encountered in the instance takes precedence over the order of elements in separator.

たとえば、値が "abcdef" であるインスタンスについて考えてみます。For example, consider an instance whose value is "abcdef". の最初の要素 separator が "ef" で、2番目の要素が "bcde" の場合、分割操作の結果は "a" と "f" になります。If the first element in separator was "ef" and the second element was "bcde", the result of the split operation would be "a" and "f". これは、"bcde" というインスタンス内の部分文字列が検出され、 separator 部分文字列 "f" が検出される前の内の要素と一致するためです。This is because the substring in the instance, "bcde", is encountered and matches an element in separator before the substring "f" is encountered.

ただし、の最初の要素 separator が "bcd" で、2番目の要素が "bc" の場合、split 操作の結果は "a" と "ef" になります。However, if the first element of separator was "bcd" and the second element was "bc", the result of the split operation would be "a" and "ef". これは、"bcd" が、 separator インスタンス内の区切り記号と一致するの最初の区切り記号であるためです。This is because "bcd" is the first delimiter in separator that matches a delimiter in the instance. 最初の要素が "bc" で、2番目の要素が "bcd" であるために、区切り記号の順序が逆になった場合、結果は "a" と "def" になります。If the order of the separators was reversed so the first element was "bc" and the second element was "bcd", the result would be "a" and "def".

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

メソッドは、 Split 返された配列オブジェクトにメモリを割り当て、 String 配列要素ごとにオブジェクトを割り当てます。The Split methods allocate memory for the returned array object and a String object for each array element. アプリケーションで最適なパフォーマンスが求められる場合、またはアプリケーションでメモリ割り当てを管理することが重要な場合は、メソッドまたはメソッドを使用して IndexOf IndexOfAny Compare 文字列内の部分文字列を検索することを検討してください。If your application requires optimal performance or if managing memory allocation is critical in your application, consider using the IndexOf or IndexOfAny method, and optionally the Compare method, to locate a substring within a string.

文字列を区切り文字で分割する場合 IndexOf は、メソッドまたはメソッドを使用し IndexOfAny て、文字列内の区切り記号を検索します。If you are splitting a string at a separator character, use the IndexOf or IndexOfAny method to locate a separator character in the string. 区切り文字列で文字列を分割する場合は、メソッドまたはメソッドを使用して、 IndexOf IndexOfAny 区切り記号文字列の最初の文字を検索します。If you are splitting a string at a separator string, use the IndexOf or IndexOfAny method to locate the first character of the separator string. 次に、メソッドを使用して、 Compare その最初の文字の後の文字が区切り記号文字列の残りの文字と等しいかどうかを確認します。Then use the Compare method to determine whether the characters after that first character are equal to the remaining characters of the separator string.

また、複数のメソッド呼び出しで同じ文字セットを使用して文字列を分割する場合は、 Split 1 つの配列を作成し、各メソッド呼び出しでそれを参照することを検討してください。In addition, if the same set of characters is used to split strings in multiple Split method calls, consider creating a single array and referencing it in each method call. これにより、各メソッド呼び出しのオーバーヘッドが大幅に減少します。This significantly reduces the additional overhead of each method call.

注意 (呼び出し元)

以前のバージョンでは、メソッドに文字が含まれていない、または文字を含んでいないが渡された場合、メソッドは文字列をトリミングするのとは .NET Framework 3.5.NET Framework 3.5 Split(Char[]) 異なり、 separator null 少し異なる空白文字のセットを使用して文字列を分割し Trim(Char[]) ます。In .NET Framework 3.5.NET Framework 3.5 and earlier versions, if the Split(Char[]) method is passed a separator that is null or contains no characters, the method uses a slightly different set of white-space characters to split the string than the Trim(Char[]) method does to trim the string. .NET Framework 4 以降では、どちらのメソッドも、同じ Unicode の空白文字のセットを使用します。Starting with .NET Framework 4, both methods use an identical set of Unicode white-space characters.

適用対象

Split(String[], StringSplitOptions)

指定された 1 つの区切り文字列およびオプション (任意) に基づいて文字列を部分文字列に分割します。Splits a string into substrings based on a specified delimiting string and, optionally, options.

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[]

この文字列から部分文字列を取り出すために区切り文字として使用する文字列の配列、区切り文字が含まれていない空の配列、または nullAn array of strings that delimit the substrings in this string, an empty array that contains no delimiters, or null.

options
StringSplitOptions

部分文字列をトリミングして空の部分文字列を含めるかどうかを指定する列挙値のビットごとの組み合わせ。A bitwise combination of the enumeration values that specifies whether to trim substrings and include empty substrings.

戻り値

String[]

この文字列を、separator 配列のいずれかまたは複数の要素 (文字列) で区切ることによって取り出された部分文字列を格納する配列。An array whose elements contain the substrings in this string that are delimited by one or more strings in separator. 詳細については、「解説」を参照してください。For more information, see the Remarks section.

属性

例外

optionsStringSplitOptions 値のいずれでもありません。options is not one of the StringSplitOptions values.

次の例では、文字列のメソッドを呼び出して、その String.Split(String[], StringSplitOptions) パラメーターをおよびと等しい配列の違いを示し options StringSplitOptions.None StringSplitOptions.RemoveEmptyEntries ます。The following example illustrates the difference in the arrays returned by calling a string's String.Split(String[], StringSplitOptions) method with its options parameter equal to StringSplitOptions.None and StringSplitOptions.RemoveEmptyEntries.

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

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

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

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

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

次の例では、句読点と空白文字を含む区切り記号の配列を定義しています。The following example defines an array of separators that include punctuation and white-space characters. この配列をの値と共 StringSplitOptions.RemoveEmptyEntries にメソッドに渡すと、 Split(String[], StringSplitOptions) 文字列の個々の単語で構成される配列が返されます。Passing this array along with a value of StringSplitOptions.RemoveEmptyEntries to the Split(String[], StringSplitOptions) method returns an array that consists of the individual words from the string.

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
    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 ください。Note that the method is called with the options argument set to StringSplitOptions.RemoveEmptyEntries. これにより、 String.Empty 区切り記号と空白文字の間の空の部分文字列の一致を表す値を、返された配列に含めることができなくなります。This prevents the returned array from including String.Empty values that represent empty substring matches between punctuation marks and white-space characters.

注釈

文字列が既知の文字列セットで区切られている場合は、メソッドを使用して、文字列を Split 部分文字列に分割できます。When a string is delimited by a known set of strings, you can use the Split method to separate it into substrings.

区切り記号文字列は、返される配列の要素には含まれません。Delimiter strings are not included in the elements of the returned array. たとえば、 separator 配列に文字列 "--" が含まれていて、現在の文字列インスタンスの値が "aa--bb--cc" である場合、メソッドは、"aa"、"bb"、および "cc" という3つの要素を含む配列を返します。For example, if the separator array includes the string "--" and the value of the current string instance is "aa--bb--cc", the method returns an array that contains three elements: "aa", "bb", and "cc".

このインスタンスに内のいずれの文字列も含まれていない場合 separator 、返される配列は、このインスタンスを格納する1つの要素で構成されます。If this instance does not contain any of the strings in separator, the returned array consists of a single element that contains this instance.

optionsパラメーターがで、 RemoveEmptyEntries このインスタンスの長さがゼロの場合、メソッドは空の配列を返します。If the options parameter is RemoveEmptyEntries and the length of this instance is zero, the method returns an empty array.

の各要素は separator 、1つ以上の文字で構成される個別の区切り記号を定義します。Each element of separator defines a separate delimiter that consists of one or more characters. options引数がであり、2つの区切り記号が隣接している場合 None 、またはこのインスタンスの先頭または末尾に区切り記号がある場合、対応する配列要素にはが含まれ String.Empty ます。If the options argument is None, and two delimiters are adjacent or a delimiter is found at the beginning or end of this instance, the corresponding array element contains String.Empty. たとえば、に separator "-" と "" の2つの要素が含まれている場合、 _ 文字列インスタンスの値は "- _ aa-" で、 _ 引数の値 options はです None 。このメソッドは、次の5つの要素を持つ文字列配列を返します。For example, if separator includes two elements, "-" and "_", the value of the string instance is "-_aa-_", and the value of the options argument is None, the method returns a string array with the following five elements:

  1. String.Empty。インデックス0の "-" 部分文字列の前にある空の文字列を表します。String.Empty, which represents the empty string that precedes the "-" substring at index 0.

  2. String.Empty。インデックス0の "-" 部分文字列とインデックス1の "" 部分文字列の間の空の文字列を表します。String.Empty, which represents the empty string between the "-" substring at index 0 and the "" substring at index 1.

  3. "aa"。"aa".

  4. String.Empty。インデックス4の "-" 部分文字列の後にある空の文字列を表します。String.Empty, which represents the empty string that follows the "-" substring at index 4.

  5. String.Empty。インデックス5の "" 部分文字列の後にある空の文字列を表します。String.Empty, which represents the empty string that follows the "" substring at index 5.

区切り記号配列The separator array

内のいずれかの要素 separator が複数の文字で構成されている場合、部分文字列全体が区切り記号と見なされます。If any of the elements in separator consists of multiple characters, the entire substring is considered a delimiter. たとえば、内のいずれかの要素 separator が "10" である場合、文字列 "This10is10a10string" を分割しようとしています。For example, if one of the elements in separator is "10", attempting to split the string "This10is10a10string." は、次の4つの要素から成る配列を返します: {"This"、"is"、"a"、"string"returns the following four-element array: { "This", "is", "a", "string." }.}.

separatorパラメーターがである null か、空でない文字列が含まれていない場合、空白文字は区切り記号と見なされます。If the separator parameter is null or contains no non-empty strings, white-space characters are assumed to be the delimiters. 空白文字は Unicode 規格によって定義され、 Char.IsWhiteSpace メソッドが true 渡された場合はを返します。White-space characters are defined by the Unicode standard and the Char.IsWhiteSpace method returns true if they are passed to it.

パラメーターにを渡すには null 、の型を指定して、 string[] separator null 他のいくつかのオーバーロード (など) からの呼び出しを明確にする必要があり Split(Char[], StringSplitOptions) ます。To pass null for the string[] separator parameter, you must indicate the type of the null to disambiguate the call from some other overloads, such as Split(Char[], StringSplitOptions). 次の例は、このオーバーロードを明確に識別するいくつかの方法を示しています。The following example shows several ways to unambiguously identify this overload.

string phrase = "The quick  brown fox";

_ = phrase.Split(default(string[]), StringSplitOptions.RemoveEmptyEntries);

_ = phrase.Split((string[])null, StringSplitOptions.RemoveEmptyEntries);

_ = phrase.Split(null as string[], StringSplitOptions.RemoveEmptyEntries);
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)

比較の詳細Comparison details

メソッドは、 Split パラメーター内の1つ以上の文字列で区切られたこの文字列の部分文字列を抽出 separator し、それらの部分文字列を配列の要素として返します。The Split method extracts the substrings in this string that are delimited by one or more of the strings in the separator parameter, and returns those substrings as elements of an array.

メソッドは、 Split 大文字と小文字を区別する序数の並べ替え規則を使用して比較を実行することで、区切り記号を検索します。The Split method looks for delimiters by performing comparisons using case-sensitive ordinal sort rules. 単語、文字列、および序数の並べ替えの詳細については、列挙体を参照してください System.Globalization.CompareOptionsFor more information about word, string, and ordinal sorts, see the System.Globalization.CompareOptions enumeration.

メソッドは、 Split separator 値が null または空の文字列 ("") であるの要素を無視します。The Split method ignores any element of separator whose value is null or the empty string ("").

の文字列に共通の文字が含まれている場合に、あいまいな結果を避けるために、 separator Split 操作は最初からインスタンスの値の末尾まで進み、インスタンスの区切り記号と等しいの最初の要素と一致し separator ます。To avoid ambiguous results when strings in separator have characters in common, the Split operation proceeds from the beginning to the end of the value of the instance, and matches the first element in separator that is equal to a delimiter in the instance. インスタンスでの部分文字列の出現順序は、の要素の順序よりも優先され separator ます。The order in which substrings are encountered in the instance takes precedence over the order of elements in separator.

たとえば、値が "abcdef" であるインスタンスについて考えてみます。For example, consider an instance whose value is "abcdef". の最初の要素 separator が "ef" で、2番目の要素が "bcde" の場合、split 操作の結果は、"a" と "f" の2つの要素を含む文字列配列になります。If the first element in separator was "ef" and the second element was "bcde", the result of the split operation would be a string array that contains two elements, "a" and "f". これは、"bcde" というインスタンス内の部分文字列が検出され、 separator 部分文字列 "f" が検出される前の内の要素と一致するためです。This is because the substring in the instance, "bcde", is encountered and matches an element in separator before the substring "f" is encountered.

ただし、の最初の要素 separator が "bcd" で、2番目の要素が "bc" の場合、split 操作の結果は、"a" と "ef" の2つの要素を含む文字列配列になります。However, if the first element of separator was "bcd" and the second element was "bc", the result of the split operation would be a string array that contains two elements, "a" and "ef". これは、"bcd" が、 separator インスタンス内の区切り記号と一致するの最初の区切り記号であるためです。This is because "bcd" is the first delimiter in separator that matches a delimiter in the instance. 最初の要素が "bc" で、2番目の要素が "bcd" であるために、区切り記号の順序が逆になった場合、結果は、"a" と "def" の2つの要素を含む文字列配列になります。If the order of the separators was reversed so the first element was "bc" and the second element was "bcd", the result would be a string array that contains two elements, "a" and "def".

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

メソッドは、 Split 返された配列オブジェクトにメモリを割り当て、 String 配列要素ごとにオブジェクトを割り当てます。The Split methods allocate memory for the returned array object and a String object for each array element. アプリケーションで最適なパフォーマンスが求められる場合、またはアプリケーションでメモリ割り当てを管理することが重要な場合は、メソッドまたはメソッドを使用して IndexOf IndexOfAny Compare 文字列内の部分文字列を検索することを検討してください。If your application requires optimal performance or if managing memory allocation is critical in your application, consider using the IndexOf or IndexOfAny method, and optionally the Compare method, to locate a substring within a string.

文字列を区切り文字で分割する場合 IndexOf は、メソッドまたはメソッドを使用し IndexOfAny て、文字列内の区切り記号を検索します。If you are splitting a string at a separator character, use the IndexOf or IndexOfAny method to locate a separator character in the string. 区切り文字列で文字列を分割する場合は、メソッドまたはメソッドを使用して、 IndexOf IndexOfAny 区切り記号文字列の最初の文字を検索します。If you are splitting a string at a separator string, use the IndexOf or IndexOfAny method to locate the first character of the separator string. 次に、メソッドを使用して、 Compare その最初の文字の後の文字が区切り記号文字列の残りの文字と等しいかどうかを確認します。Then use the Compare method to determine whether the characters after that first character are equal to the remaining characters of the separator string.

また、複数のメソッド呼び出しで同じ文字セットを使用して文字列を分割する場合は、 Split 1 つの配列を作成し、各メソッド呼び出しでそれを参照することを検討してください。In addition, if the same set of characters is used to split strings in multiple Split method calls, consider creating a single array and referencing it in each method call. これにより、各メソッド呼び出しのオーバーヘッドが大幅に減少します。This significantly reduces the additional overhead of each method call.

注意 (呼び出し元)

以前のバージョンでは、メソッドに文字が含まれていない、または文字を含んでいないが渡された場合、メソッドは文字列をトリミングするのとは .NET Framework 3.5.NET Framework 3.5 Split(Char[]) 異なり、 separator null 少し異なる空白文字のセットを使用して文字列を分割し Trim(Char[]) ます。In .NET Framework 3.5.NET Framework 3.5 and earlier versions, if the Split(Char[]) method is passed a separator that is null or contains no characters, the method uses a slightly different set of white-space characters to split the string than the Trim(Char[]) method does to trim the string. .NET Framework 4 以降では、どちらのメソッドも、同じ Unicode の空白文字のセットを使用します。Starting with .NET Framework 4, both methods use an identical set of Unicode white-space characters.

適用対象

Split(String, Int32, StringSplitOptions)

指定された 1 つの区切り文字列およびオプション (任意) に基づいて文字列を最大数の部分文字列に分割します。Splits a string into a maximum number of substrings based on a specified delimiting string and, optionally, options.

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

このインスタンス内の部分文字列を区切る文字列。A string that delimits the substrings in this instance.

count
Int32

配列に必要な要素の最大数。The maximum number of elements expected in the array.

options
StringSplitOptions

部分文字列をトリミングして空の部分文字列を含めるかどうかを指定する列挙値のビットごとの組み合わせ。A bitwise combination of the enumeration values that specifies whether to trim substrings and include empty substrings.

戻り値

String[]

separator で区切られた、このインスタンスの最大 count の部分文字列を格納する配列。An array that contains at most count substrings from this instance that are delimited by separator.

注釈

文字列が既に1回分割されていて count も、文字列の末尾に到達していない場合、返された配列の最後の文字列には、このインスタンスの残りの末尾の部分文字列が含まれます。If the string has already been split count - 1 times, but the end of the string has not been reached, then the last string in the returned array will contain this instance's remaining trailing substring, untouched.

適用対象

Split(Char[], StringSplitOptions)

指定された区切り文字およびオプションに基づいて文字列を部分文字列に分割します。Splits a string into substrings based on specified delimiting characters and options.

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[]

この文字列から部分文字列を取り出すために区切り文字として使用する文字の配列、区切り文字が含まれていない空の配列、または nullAn array of characters that delimit the substrings in this string, an empty array that contains no delimiters, or null.

options
StringSplitOptions

部分文字列をトリミングして空の部分文字列を含めるかどうかを指定する列挙値のビットごとの組み合わせ。A bitwise combination of the enumeration values that specifies whether to trim substrings and include empty substrings.

戻り値

String[]

この文字列を、separator 配列のいずれかまたは複数の要素 (文字) で区切ることによって取り出された部分文字列を格納する配列。An array whose elements contain the substrings in this string that are delimited by one or more characters in separator. 詳細については、「解説」を参照してください。For more information, see the Remarks section.

属性

例外

optionsStringSplitOptions 値のいずれでもありません。options is not one of the StringSplitOptions values.

次の例では、 StringSplitOptions 列挙体を使用して、メソッドによって生成される部分文字列を含めたり除外したりし Split ます。The following example uses the StringSplitOptions enumeration to include or exclude substrings generated by the Split method.

// 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]>

*/
    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 ) は、返される配列の要素には含まれません。Delimiter characters (the characters in the separator array) are not included in the elements of the returned array. たとえば、 separator 配列に文字 "-" が含まれていて、現在の文字列インスタンスの値が "aa-bb-cc" である場合、メソッドは、"aa"、"bb"、および "cc" の3つの要素を含む配列を返します。For example, if the separator array includes the character "-" and the value of the current string instance is "aa-bb-cc", the method returns an array that contains three elements: "aa", "bb", and "cc".

このインスタンスに内のいずれの文字も含まれていない場合 separator 、返される配列は、このインスタンスを格納する1つの要素で構成されます。If this instance does not contain any of the characters in separator, the returned array consists of a single element that contains this instance.

optionsパラメーターがで、 RemoveEmptyEntries このインスタンスの長さがゼロの場合、メソッドは空の配列を返します。If the options parameter is RemoveEmptyEntries and the length of this instance is zero, the method returns an empty array.

の各要素 separator は、1つの文字で構成される個別の区切り記号を定義します。Each element of separator defines a separate delimiter that consists of a single character. options引数がであり、2つの区切り記号が隣接している場合 None 、またはこのインスタンスの先頭または末尾に区切り記号がある場合、対応する配列要素にはが含まれ String.Empty ます。If the options argument is None, and two delimiters are adjacent or a delimiter is found at the beginning or end of this instance, the corresponding array element contains String.Empty. たとえば、に separator 2 つの要素が含まれて '-' おり、 '_' 文字列インスタンスの値が " _ -aa-" で、 _ 引数の値がである場合、 options None メソッドは次の5つの要素を持つ文字列配列を返します。For example, if separator includes two elements, '-' and '_', the value of the string instance is "-_aa-_", and the value of the options argument is None, the method returns a string array with the following five elements:

  1. String.Empty。インデックス0の "-" 文字の前にある空の文字列を表します。String.Empty, which represents the empty string that precedes the "-" character at index 0.

  2. String.Empty。インデックス0の "-" 文字とインデックス1の "" 文字の間の空の文字列を表します。String.Empty, which represents the empty string between the "-" character at index 0 and the "" character at index 1.

  3. "aa"。"aa".

  4. String.Empty。インデックス4の "-" 文字の後に続く空の文字列を表します。String.Empty, which represents the empty string that follows the "-" character at index 4.

  5. String.Empty。インデックス5の "" 文字の後に続く空の文字列を表します。String.Empty, which represents the empty string that follows the "" character at index 5.

区切り記号配列The separator array

separatorパラメーターがであるか、文字を含んでいない場合は null 、空白文字が区切り記号と見なされます。If the separator parameter is null or contains no characters, white-space characters are assumed to be the delimiters. 空白文字は Unicode 規格によって定義され、 Char.IsWhiteSpace メソッドが true 渡された場合はを返します。White-space characters are defined by the Unicode standard and the Char.IsWhiteSpace method returns true if they are passed to it.

パラメーターにを渡すには null 、の型を指定して、 char[] separator null 他のいくつかのオーバーロード (など) からの呼び出しを明確にする必要があり Split(String[], StringSplitOptions) ます。To pass null for the char[] separator parameter, you must indicate the type of the null to disambiguate the call from some other overloads, such as Split(String[], StringSplitOptions). 次の例は、このオーバーロードを明確に識別するいくつかの方法を示しています。The following example shows several ways to unambiguously identify this overload.

string phrase = "The quick  brown fox";

_ = phrase.Split(default(char[]), StringSplitOptions.RemoveEmptyEntries);

_ = phrase.Split((char[])null, StringSplitOptions.RemoveEmptyEntries);

_ = phrase.Split(null as char[], StringSplitOptions.RemoveEmptyEntries);
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)

比較の詳細Comparison details

メソッドは、 Split パラメーターの1つ以上の文字で区切られたこの文字列の部分文字列を抽出 separator し、それらの部分文字列を配列の要素として返します。The Split method extracts the substrings in this string that are delimited by one or more of the characters in the separator parameter, and returns those substrings as elements of an array.

メソッドは、 Split 大文字と小文字を区別する序数の並べ替え規則を使用して比較を実行することで、区切り記号を検索します。The Split method looks for delimiters by performing comparisons using case-sensitive ordinal sort rules. 単語、文字列、および序数の並べ替えの詳細については、列挙体を参照してください System.Globalization.CompareOptionsFor more information about word, string, and ordinal sorts, see the System.Globalization.CompareOptions enumeration.

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

メソッドは、 Split 返された配列オブジェクトにメモリを割り当て、 String 配列要素ごとにオブジェクトを割り当てます。The Split methods allocate memory for the returned array object and a String object for each array element. アプリケーションで最適なパフォーマンスが求められる場合、またはアプリケーションでメモリ割り当てを管理することが重要な場合は、メソッドまたはメソッドを使用して IndexOf IndexOfAny Compare 文字列内の部分文字列を検索することを検討してください。If your application requires optimal performance or if managing memory allocation is critical in your application, consider using the IndexOf or IndexOfAny method, and optionally the Compare method, to locate a substring within a string.

文字列を区切り文字で分割する場合 IndexOf は、メソッドまたはメソッドを使用し IndexOfAny て、文字列内の区切り記号を検索します。If you are splitting a string at a separator character, use the IndexOf or IndexOfAny method to locate a separator character in the string. 区切り文字列で文字列を分割する場合は、メソッドまたはメソッドを使用して、 IndexOf IndexOfAny 区切り記号文字列の最初の文字を検索します。If you are splitting a string at a separator string, use the IndexOf or IndexOfAny method to locate the first character of the separator string. 次に、メソッドを使用して、 Compare その最初の文字の後の文字が区切り記号文字列の残りの文字と等しいかどうかを確認します。Then use the Compare method to determine whether the characters after that first character are equal to the remaining characters of the separator string.

また、複数のメソッド呼び出しで同じ文字セットを使用して文字列を分割する場合は、 Split 1 つの配列を作成し、各メソッド呼び出しでそれを参照することを検討してください。In addition, if the same set of characters is used to split strings in multiple Split method calls, consider creating a single array and referencing it in each method call. これにより、各メソッド呼び出しのオーバーヘッドが大幅に減少します。This significantly reduces the additional overhead of each method call.

注意 (呼び出し元)

以前のバージョンでは、メソッドに文字が含まれていない、または文字を含んでいないが渡された場合、メソッドは文字列をトリミングするのとは .NET Framework 3.5.NET Framework 3.5 Split(Char[]) 異なり、 separator null 少し異なる空白文字のセットを使用して文字列を分割し Trim(Char[]) ます。In .NET Framework 3.5.NET Framework 3.5 and earlier versions, if the Split(Char[]) method is passed a separator that is null or contains no characters, the method uses a slightly different set of white-space characters to split the string than the Trim(Char[]) method does to trim the string. .NET Framework 4 以降では、どちらのメソッドも、同じ Unicode の空白文字のセットを使用します。Starting with .NET Framework 4, both methods use an identical set of Unicode white-space characters.

適用対象

Split(Char[], Int32)

指定された区切り文字に基づいて文字列を最大数の部分文字列に分割します。Splits a string into a maximum number of substrings based on specified delimiting characters.

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[]

この文字列から部分文字列を取り出すために区切り文字として使用する文字の配列、区切り文字が含まれていない空の配列、または nullAn array of characters that delimit the substrings in this string, an empty array that contains no delimiters, or null.

count
Int32

返される最大の部分文字列数。The maximum number of substrings to return.

戻り値

String[]

このインスタンスを、separator 配列のいずれかまたは複数の要素 (文字) で区切ることによって取り出された部分文字列を格納する配列。An array whose elements contain the substrings in this instance that are delimited by one or more characters in separator. 詳細については、「解説」を参照してください。For more information, see the Remarks section.

例外

count が負の値です。count is negative.

次の例では、を count 使用して、によって返される文字列の数を制限する方法を示し Split ます。The following example demonstrates how count can be used to limit the number of strings returned by Split.

string name = "Alex Johnson III";

string[] subs = name.Split(null, 2);

string firstName = subs[0];
string lastName;
if (subs.Length > 1)
{
    lastName = subs[1];
}

// firstName = "Alex"
// lastName = "Johnson III"
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"

注釈

区切り文字は、返される配列の要素には含まれません。Delimiter characters are not included in the elements of the returned array.

このインスタンスに内のいずれの文字も含まれていない場合 separator 、返される配列は、このインスタンスを格納する1つの要素で構成されます。If this instance does not contain any of the characters in separator, the returned array consists of a single element that contains this instance. countが0の場合は、空の配列が返されます。If count is zero, an empty array is returned.

separatorパラメーターがであるか、文字を含んでいない場合は null 、空白文字が区切り記号と見なされます。If the separator parameter is null or contains no characters, white-space characters are assumed to be the delimiters. 空白文字は Unicode 規格によって定義され、 Char.IsWhiteSpace メソッドが true 渡された場合はを返します。White-space characters are defined by the Unicode standard and the Char.IsWhiteSpace method returns true if they are passed to it.

の各要素 separator は、個別の区切り文字を定義します。Each element of separator defines a separate delimiter character. 2つの区切り記号が隣接している場合、またはこのインスタンスの先頭または末尾に区切り記号がある場合、対応する配列要素にはが含まれ Empty ます。If two delimiters are adjacent, or a delimiter is found at the beginning or end of this instance, the corresponding array element contains Empty.

このインスタンスに複数の部分文字列が含まれている場合 count 、最初の count - 1 部分文字列が戻り値の最初の要素に返され、 count - 1 このインスタンスの残りの文字が戻り値の最後の要素に返されます。If there are more than count substrings in this instance, the first count - 1 substrings are returned in the first count - 1 elements of the return value, and the remaining characters in this instance are returned in the last element of the return value.

countが部分文字列の数より大きい場合は、使用可能な部分文字列が返され、例外はスローされません。If count is greater than the number of substrings, the available substrings are returned and no exception is thrown.

次の表は、いくつかの例を示しています。The following table shows some examples.

LanguageLanguage 文字列値String value 区切り記号Separator 返された配列Returned array
C#C# "42, 12, 19""42, 12, 19" 新しい Char [] {', ', ' '}new Char[] {',', ' '} {"42", "", "12", "", "19"}{"42", "", "12", "", "19"}
Visual BasicVisual Basic "42, 12, 19""42, 12, 19" Char () = {"," c, "" c})Char() = {","c, " "c}) {"42", "", "12", "", "19"}{"42", "", "12", "", "19"}
C#C# "42.. 12.. 19""42..12..19." 新しい Char [] {'}new Char[] {'.'} {"42"、""、"12"、""、"19"、""}{"42", "", "12", "", "19", ""}
Visual BasicVisual Basic "42.. 12.. 19""42..12..19." Char () = {"."40u-cChar() = {"."c} {"42"、""、"12"、""、"19"、""}{"42", "", "12", "", "19", ""}
C#C# バナナ"Banana" 新しい Char [] {'}new Char[] {'.'} {"バナナ"}{"Banana"}
Visual BasicVisual Basic バナナ"Banana" Char () = {"."40u-cChar() = {"."c} {"バナナ"}{"Banana"}
C#C# "Darb\nSmarba""Darb\nSmarba" 新しい Char [] {}new Char[] {} {"Darb", "Smarba"}{"Darb", "Smarba"}
Visual BasicVisual Basic "Darb" & vbLf & "Smarba""Darb" & vbLf & "Smarba" Char () = {}Char() = {} {"Darb", "Smarba"}{"Darb", "Smarba"}
C#C# "Darb\nSmarba""Darb\nSmarba" nullnull {"Darb", "Smarba"}{"Darb", "Smarba"}
Visual BasicVisual Basic "Darb" & vbLf & "Smarba""Darb" & vbLf & "Smarba" なしNothing {"Darb", "Smarba"}{"Darb", "Smarba"}

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

メソッドは、 Split 返された配列オブジェクトにメモリを割り当て、 String 配列要素ごとにオブジェクトを割り当てます。The Split methods allocate memory for the returned array object and a String object for each array element. アプリケーションで最適なパフォーマンスが求められる場合、またはアプリケーションでメモリ割り当てを管理することが重要な場合は、メソッドまたはメソッドを使用して IndexOf IndexOfAny Compare 文字列内の部分文字列を検索することを検討してください。If your application requires optimal performance or if managing memory allocation is critical in your application, consider using the IndexOf or IndexOfAny method, and optionally the Compare method, to locate a substring within a string.

文字列を区切り文字で分割する場合 IndexOf は、メソッドまたはメソッドを使用し IndexOfAny て、文字列内の区切り記号を検索します。If you are splitting a string at a separator character, use the IndexOf or IndexOfAny method to locate a separator character in the string. 区切り文字列で文字列を分割する場合は、メソッドまたはメソッドを使用して、 IndexOf IndexOfAny 区切り記号文字列の最初の文字を検索します。If you are splitting a string at a separator string, use the IndexOf or IndexOfAny method to locate the first character of the separator string. 次に、メソッドを使用して、 Compare その最初の文字の後の文字が区切り記号文字列の残りの文字と等しいかどうかを確認します。Then use the Compare method to determine whether the characters after that first character are equal to the remaining characters of the separator string.

また、複数のメソッド呼び出しで同じ文字セットを使用して文字列を分割する場合は、 Split 1 つの配列を作成し、各メソッド呼び出しでそれを参照することを検討してください。In addition, if the same set of characters is used to split strings in multiple Split method calls, consider creating a single array and referencing it in each method call. これにより、各メソッド呼び出しのオーバーヘッドが大幅に減少します。This significantly reduces the additional overhead of each method call.

注意 (呼び出し元)

以前のバージョンでは、メソッドに文字が含まれていない、または文字を含んでいないが渡された場合、メソッドは文字列をトリミングするのとは .NET Framework 3.5.NET Framework 3.5 Split(Char[]) 異なり、 separator null 少し異なる空白文字のセットを使用して文字列を分割し Trim(Char[]) ます。In .NET Framework 3.5.NET Framework 3.5 and earlier versions, if the Split(Char[]) method is passed a separator that is null or contains no characters, the method uses a slightly different set of white-space characters to split the string than the Trim(Char[]) method does to trim the string. .NET Framework 4 以降では、どちらのメソッドも、同じ Unicode の空白文字のセットを使用します。Starting with .NET Framework 4, both methods use an identical set of Unicode white-space characters.

こちらもご覧ください

適用対象

Split(Char, StringSplitOptions)

指定された 1 つの区切り文字およびオプション (任意) に基づいて文字列を部分文字列に分割します。Splits a string into substrings based on a specified delimiting character and, optionally, options.

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

この文字列内の部分文字列を区切る文字。A character that delimits the substrings in this string.

options
StringSplitOptions

部分文字列をトリミングして空の部分文字列を含めるかどうかを指定する列挙値のビットごとの組み合わせ。A bitwise combination of the enumeration values that specifies whether to trim substrings and include empty substrings.

戻り値

String[]

separator によって区切られた、このインスタンスの部分文字列を要素に格納する配列。An array whose elements contain the substrings from this instance that are delimited by separator.

適用対象

Split(String, StringSplitOptions)

指定された文字列の区切り記号に基づいて文字列を部分文字列に分割します。Splits a string into substrings that are based on the provided string separator.

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

この文字列内の部分文字列を区切る文字列。A string that delimits the substrings in this string.

options
StringSplitOptions

部分文字列をトリミングして空の部分文字列を含めるかどうかを指定する列挙値のビットごとの組み合わせ。A bitwise combination of the enumeration values that specifies whether to trim substrings and include empty substrings.

戻り値

String[]

separator によって区切られた、このインスタンスの部分文字列を要素に格納する配列。An array whose elements contain the substrings from this instance that are delimited by separator.

適用対象

Split(Char[])

指定された区切り文字に基づいて文字列を部分文字列に分割します。Splits a string into substrings based on specified delimiting characters.

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[]

区切り文字の配列、区切り文字が含まれていない空の配列、または nullAn array of delimiting characters, an empty array that contains no delimiters, or null.

戻り値

String[]

このインスタンスを separator の 1 つ以上の文字で区切った部分文字列を要素に格納する配列。An array whose elements contain the substrings from this instance that are delimited by one or more characters in separator. 詳細については、「解説」を参照してください。For more information, see the Remarks section.

次の例では、スペース文字 ( ) とタブ文字 () を区切り記号として扱うことによって、テキストブロックから個々の単語を抽出する方法を示し \t ます。The following example demonstrates how to extract individual words from a block of text by treating the space character ( ) and tab character (\t) as delimiters. 分割される文字列には、これらの文字の両方が含まれます。The string being split includes both of these characters.

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
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[]) ます。When a string is delimited by a known set of characters, you can use the Split(Char[]) method to separate it into substrings.

区切り文字は、返される配列の要素には含まれません。Delimiter characters are not included in the elements of the returned array. たとえば、区切り記号配列に文字 "-" が含まれていて、現在の文字列インスタンスの値が "aa-bb-cc" の場合、メソッドは、"aa"、"bb"、および "cc" の3つの要素を含む配列を返します。For example, if the separator array includes the character "-" and the value of the current string instance is "aa-bb-cc", the method returns an array that contains three elements: "aa", "bb", and "cc".

このインスタンスに内のいずれの文字も含まれていない場合 separator 、返される配列は、このインスタンスを格納する1つの要素で構成されます。If this instance does not contain any of the characters in separator, the returned array consists of a single element that contains this instance.

の各要素 separator は、個別の区切り文字を定義します。Each element of separator defines a separate delimiter character. 2つの区切り記号が隣接している場合、またはこのインスタンスの先頭または末尾に区切り記号がある場合、返される配列内の対応する要素にはが含まれ Empty ます。If two delimiters are adjacent, or a delimiter is found at the beginning or end of this instance, the corresponding element in the returned array contains Empty.

次の表は、いくつかの例を示しています。The following table shows some examples.

LanguageLanguage 文字列値String value 区切り記号Separator 返された配列Returned array
C#C# "42, 12, 19""42, 12, 19" 新しい Char [] {', ', ' '}new Char[] {',', ' '} {"42", "", "12", "", "19"}{"42", "", "12", "", "19"}
Visual BasicVisual Basic "42, 12, 19""42, 12, 19" Char () = {"," c, "" c})Char() = {","c, " "c}) {"42", "", "12", "", "19"}{"42", "", "12", "", "19"}
C#C# "42.. 12.. 19""42..12..19." 新しい Char [] {'}new Char[] {'.'} {"42"、""、"12"、""、"19"、""}{"42", "", "12", "", "19", ""}
Visual BasicVisual Basic "42.. 12.. 19""42..12..19." Char () = {"."40u-cChar() = {"."c} {"42"、""、"12"、""、"19"、""}{"42", "", "12", "", "19", ""}
C#C# バナナ"Banana" 新しい Char [] {'}new Char[] {'.'} {"バナナ"}{"Banana"}
Visual BasicVisual Basic バナナ"Banana" Char () = {"."40u-cChar() = {"."c} {"バナナ"}{"Banana"}
C#C# "Darb\nSmarba""Darb\nSmarba" 新しい Char [] {}new Char[] {} {"Darb", "Smarba"}{"Darb", "Smarba"}
Visual BasicVisual Basic "Darb" & vbLf & "Smarba""Darb" & vbLf & "Smarba" Char () = {}Char() = {} {"Darb", "Smarba"}{"Darb", "Smarba"}
C#C# "Darb\nSmarba""Darb\nSmarba" nullnull {"Darb", "Smarba"}{"Darb", "Smarba"}
Visual BasicVisual Basic "Darb" & vbLf & "Smarba""Darb" & vbLf & "Smarba" なしNothing {"Darb", "Smarba"}{"Darb", "Smarba"}

区切り記号配列The separator array

Separator の各要素は、1つの文字で構成される個別の区切り記号を定義します。Each element of separator defines a separate delimiter that consists of a single character.

separator引数がである null か、または文字を含んでいない場合、メソッドは空白文字を区切り記号として扱います。If the separator argument is null or contains no characters, the method treats white-space characters as the delimiters. 空白文字は Unicode 規格によって定義され Char.IsWhiteSpace true ます。空白文字が渡されると、メソッドはを返します。White-space characters are defined by the Unicode standard, and the Char.IsWhiteSpace method returns true if a white-space character is passed to it.

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

のこのオーバーロードの1つのパラメーター String.Split は文字配列ですが、次の例に示すように、1つの文字で呼び出すことができます。Although the single parameter for this overload of String.Split is a character array, you can call it with a single character, as the following example shows.

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.
    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つの文字を単一要素の文字配列として解釈します。Because the separator parameter is decorated with the ParamArrayAttribute attribute, compilers will interpret a single character as a single-element character array. これは、パラメーターを含む他のオーバーロードには当てはまりません String.Split separator 。これらのオーバーロードを引数として文字配列に明示的に渡す必要があり separator ます。This is not the case for other String.Split overloads that include a separator parameter; you must explicitly pass these overloads a character array as the separator argument.

比較の詳細Comparison details

メソッドは、 Split(Char[]) 配列内の1つ以上の文字で区切られたこの文字列の部分文字列を抽出 separator し、それらの部分文字列を配列の要素として返します。The Split(Char[]) method extracts the substrings in this string that are delimited by one or more of the characters in the separator array, and returns those substrings as elements of an array.

メソッドは、 Split(Char[]) 大文字と小文字を区別する序数の並べ替え規則を使用して比較を実行することで、区切り記号を検索します。The Split(Char[]) method looks for delimiters by performing comparisons using case-sensitive ordinal sort rules. 単語、文字列、および序数の並べ替えの詳細については、列挙体を参照してください System.Globalization.CompareOptionsFor more information about word, string, and ordinal sorts, see the System.Globalization.CompareOptions enumeration.

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

メソッドは、 Split 返された配列オブジェクトにメモリを割り当て、 String 配列要素ごとにオブジェクトを割り当てます。The Split methods allocate memory for the returned array object and a String object for each array element. アプリケーションで最適なパフォーマンスが求められる場合や、アプリケーションでメモリ割り当てを管理する必要がある場合は、 IndexOf メソッドまたはメソッドの使用を検討してください IndexOfAnyIf your application requires optimal performance or if managing memory allocation is critical in your application, consider using the IndexOf or IndexOfAny method. また、メソッドを使用して、 Compare 文字列内の部分文字列を検索することもできます。You also have the option of using the Compare method to locate a substring within a string.

文字列を区切り文字で分割するに IndexOf は、メソッドまたはメソッドを使用し IndexOfAny て、文字列内の区切り記号を検索します。To split a string at a separator character, use the IndexOf or IndexOfAny method to locate a separator character in the string. 区切り文字列で文字列を分割するには、メソッドまたはメソッドを使用して、 IndexOf IndexOfAny 区切り記号文字列の最初の文字を検索します。To split a string at a separator string, use the IndexOf or IndexOfAny method to locate the first character of the separator string. 次に、メソッドを使用して、 Compare その最初の文字の後の文字が区切り記号文字列の残りの文字と等しいかどうかを確認します。Then use the Compare method to determine whether the characters after that first character are equal to the remaining characters of the separator string.

また、複数のメソッド呼び出しで同じ文字セットを使用して文字列を分割する場合は、 Split 1 つの配列を作成し、各メソッド呼び出しでそれを参照することを検討してください。In addition, if the same set of characters is used to split strings in multiple Split method calls, consider creating a single array and referencing it in each method call. これにより、各メソッド呼び出しのオーバーヘッドが大幅に減少します。This significantly reduces the additional overhead of each method call.

注意 (呼び出し元)

以前のバージョンでは、メソッドに文字が含まれていない、または文字を含んでいないが渡された場合、メソッドは文字列をトリミングするのとは .NET Framework 3.5.NET Framework 3.5 Split(Char[]) 異なり、 separator null 少し異なる空白文字のセットを使用して文字列を分割し Trim(Char[]) ます。In .NET Framework 3.5.NET Framework 3.5 and earlier versions, if the Split(Char[]) method is passed a separator that is null or contains no characters, the method uses a slightly different set of white-space characters to split the string than the Trim(Char[]) method does to trim the string. .NET Framework 4 以降では、どちらのメソッドも、同じ Unicode の空白文字のセットを使用します。Starting with .NET Framework 4, both methods use an identical set of Unicode white-space characters.

こちらもご覧ください

適用対象