String.Split String.Split String.Split String.Split Method

定義

このインスタンス内の、指定された文字列または 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) Split(Char[], Int32, StringSplitOptions) Split(Char[], Int32, StringSplitOptions) Split(Char[], Int32, StringSplitOptions)

配列内の文字に基づいて文字列を最大数の部分文字列に分割します。Splits a string into a maximum number of substrings based on the characters in an array.

Split(Char, Int32, StringSplitOptions) Split(Char, Int32, StringSplitOptions) Split(Char, Int32, StringSplitOptions)
Split(String[], Int32, StringSplitOptions) Split(String[], Int32, StringSplitOptions) Split(String[], Int32, StringSplitOptions) Split(String[], Int32, StringSplitOptions)

配列内の文字列に基づいて文字列を最大数の部分文字列に分割します。Splits a string into a maximum number of substrings based on the strings in an array. 部分文字列が空の配列の要素を含めるかどうかを指定することができます。You can specify whether the substrings include empty array elements.

Split(String[], StringSplitOptions) Split(String[], StringSplitOptions) Split(String[], StringSplitOptions) Split(String[], StringSplitOptions)

配列内の文字列に基づいて文字列を部分文字列に分割します。Splits a string into substrings based on the strings in an array. 部分文字列が空の配列の要素を含めるかどうかを指定することができます。You can specify whether the substrings include empty array elements.

Split(String, Int32, StringSplitOptions) Split(String, Int32, StringSplitOptions) Split(String, Int32, StringSplitOptions)
Split(Char[], StringSplitOptions) Split(Char[], StringSplitOptions) Split(Char[], StringSplitOptions) Split(Char[], StringSplitOptions)

配列内の文字に基づいて文字列を部分文字列に分割します。Splits a string into substrings based on the characters in an array. 部分文字列が空の配列の要素を含めるかどうかを指定することができます。You can specify whether the substrings include empty array elements.

Split(Char[], Int32) Split(Char[], Int32) Split(Char[], Int32) Split(Char[], Int32)

配列内の文字に基づいて文字列を最大数の部分文字列に分割します。Splits a string into a maximum number of substrings based on the characters in an array. 返される部分文字列の最大数を指定します。You also specify the maximum number of substrings to return.

Split(Char, StringSplitOptions) Split(Char, StringSplitOptions) Split(Char, StringSplitOptions)
Split(String, StringSplitOptions) Split(String, StringSplitOptions) Split(String, StringSplitOptions)
Split(Char[]) Split(Char[]) Split(Char[]) Split(Char[])

配列内の文字に基づいて文字列を部分文字列に分割します。Splits a string into substrings that are based on the characters in an array.

注釈

Splitは、区切られた文字列を部分文字列に分割する場合に使用します。Split is used to break a delimited string into substrings. 文字配列を使用して、0個、1個、または複数の区切り文字Split(Char[]) (メソッド) を指定できます。または、文字配列を使用して、0個、1個、または複数の区切り文字列を指定できます。You can use either a character array to specify zero, one, or multiple delimiting characters (the Split(Char[]) method), or you can use a character array to specify zero, one, or multiple delimiting strings. メソッドの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 determine whether empty strings are included in the returned substrings (the Split(Char[], StringSplitOptions) and Split(String[], StringSplitOptions) methods, or to do both (the Split(Char[], Int32, StringSplitOptions) and Split(String[], Int32, StringSplitOptions) methods).

注意

この記事の C# 例は、Try.NET インライン コード ランナーとプレイグラウンドで実行されます。The C# examples in this article run in the Try.NET inline code runner and playground. [実行] ボタンを選択すると、対話型ウィンドウで例が実行されます。Select the Run button to run an example in an interactive window. コードを実行したら、コードを変更し、 [実行] をもう一度選択して変更後のコードを実行できます。Once you execute the code, you can modify it and run the modified code by selecting Run again. 変更後のコードが対話型ウィンドウで実行されるか、コンパイルできなかった場合、対話型ウィンドウにすべての C# コンパイラ エラー メッセージが表示されます。The modified code either runs in the interactive window or, if compilation fails, the interactive window displays all C# compiler error messages.

文字列分割の代替手段Alternatives to String.Split

Splitメソッドは、区切られた文字列を部分文字列に分割するのに常に最適な方法であるとは限りません。The Split method is not always the best way to break a delimited string into substrings. 区切られた文字列の一部の部分文字列を抽出したくない場合、または区切り文字のセットではなくパターンに基づいて文字列を解析する場合は、次の代替手段を検討してください。If 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 the following alternatives.

正規表現Regular expressions

文字列が固定パターンに準拠している場合は、正規表現を使用してその要素を抽出して処理できます。If your strings conform to a fixed pattern, you can use a regular expression to extract and handle their elements. たとえば、文字列の形式が "数値オペランド数値" の場合、正規表現を使用して文字列の要素を抽出し、処理することができます。For example, if strings take the form "number operand number" you can use a regular expression to extract and handle the string's elements. 次に例を示します。Here's an example:

   String[] expressions = { "16 + 21", "31 * 3", "28 / 3",
                            "42 - 18", "12 * 7",
                            "2, 4, 6, 8" };
   String pattern = @"(\d+)\s+([-+*/])\s+(\d+)";
   foreach (var expression in expressions)
      foreach (System.Text.RegularExpressions.Match m in 
      System.Text.RegularExpressions.Regex.Matches(expression, pattern)) {
         int value1 = Int32.Parse(m.Groups[1].Value);
         int value2 = Int32.Parse(m.Groups[3].Value);
         switch (m.Groups[2].Value)
         {
            case "+":
               Console.WriteLine("{0} = {1}", m.Value, value1 + value2);
               break;
            case "-":
               Console.WriteLine("{0} = {1}", m.Value, value1 - value2);
               break;
            case "*":
               Console.WriteLine("{0} = {1}", m.Value, value1 * value2);
               break;
            case "/":
               Console.WriteLine("{0} = {1:N2}", m.Value, value1 / value2);
               break;
         }
      }
// The example displays the following output:
//       16 + 21 = 37
//       31 * 3 = 93
//       28 / 3 = 9.33
//       42 - 18 = 24
//       12 * 7 = 84
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim expressions() As String = { "16 + 21", "31 * 3", "28 / 3",
                                      "42 - 18", "12 * 7",
                                      "2, 4, 6, 8" }

      Dim pattern As String = "(\d+)\s+([-+*/])\s+(\d+)"
      For Each expression In expressions
         For Each m As Match in Regex.Matches(expression, pattern)
            Dim value1 As Integer = Int32.Parse(m.Groups(1).Value)
            Dim value2 As Integer = Int32.Parse(m.Groups(3).Value)
            Select Case m.Groups(2).Value
               Case "+"
                  Console.WriteLine("{0} = {1}", m.Value, value1 + value2)
               Case "-"
                  Console.WriteLine("{0} = {1}", m.Value, value1 - value2)
               Case "*"
                  Console.WriteLine("{0} = {1}", m.Value, value1 * value2)
               Case "/"
                  Console.WriteLine("{0} = {1:N2}", m.Value, value1 / value2)
            End Select
         Next
      Next
   End Sub
End Module
' The example displays the following output:
'       16 + 21 = 37
'       31 * 3 = 93
'       28 / 3 = 9.33
'       42 - 18 = 24
'       12 * 7 = 84

正規表現パターン(\d+)\s+([-+*/])\s+(\d+)は次のように定義されています。The regular expression pattern (\d+)\s+([-+*/])\s+(\d+) is defined like this:

パターンPattern 説明Description
(\d+) 1 個以上の 10 進数と一致します。Match one or more decimal digits. これが最初のキャプチャ グループです。This is the first capturing group.
\s+ 1個以上の空白文字と一致します。Match one or more white-space characters.
([-+*/]) 算術演算子の符号 (+、-、*、/) と一致します。Match an arithmetic operator sign (+, -, *, or /). これが 2 番目のキャプチャ グループです。This is the second capturing group.
\s+ 1個以上の空白文字と一致します。Match one or more white-space characters.
(\d+) 1 個以上の 10 進数と一致します。Match one or more decimal digits. これが 3 番目のキャプチャ グループです。This is the third capturing group.

また、正規表現を使用して、固定された文字のセットではなく、パターンに基づいて文字列から部分文字列を抽出することもできます。You can also use a regular expression to extract substrings from a string based on a pattern rather than a fixed set of characters. これは、次のいずれかの条件が発生した場合の一般的なシナリオです。This is a common scenario when either of these conditions occurs:

  • 1つ以上の区切り文字が、 Stringインスタンス内の区切り記号として機能するとは限りません。One or more of the delimiter characters does not always serve as a delimiter in the String instance.

  • 区切り文字のシーケンスと数は、変数または unknown です。The sequence and number of delimiter characters is variable or unknown.

たとえば、メソッドをSplit使用して次の文字列を分割することはできません。これC#は、 vbCrLf (in) または (Visual Basic) 文字の\n数が可変であり、常に区切り記号として機能しないためです。For example, the Split method cannot be used to split the following string, because the number of \n (in C#) or vbCrLf (in Visual Basic) characters is variable, and they don't always serve as delimiters.

[This is captured\ntext.]\n\n[\n[This is more captured text.]\n]  
\n[Some more captured text:\n   Option1\n   Option2][Terse text.]  

次の例に示すように、正規表現では、この文字列を簡単に分割できます。A regular expression can split this string easily, as the following example shows.

String input = "[This is captured\ntext.]\n\n[\n" +
               "[This is more captured text.]\n]\n" +
               "[Some more captured text:\n   Option1" +
               "\n   Option2][Terse text.]";
String pattern = @"\[([^\[\]]+)\]";
int ctr = 0;
foreach (System.Text.RegularExpressions.Match m in 
   System.Text.RegularExpressions.Regex.Matches(input, pattern))
   Console.WriteLine("{0}: {1}", ++ctr, m.Groups[1].Value);
// The example displays the following output:
//       1: This is captured
//       text.
//       2: This is more captured text.
//       3: Some more captured text:
//          Option1
//          Option2
//       4: Terse text.
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim input As String = String.Format("[This is captured{0}text.]" +
                                          "{0}{0}[{0}[This is more " +
                                          "captured text.]{0}{0}" +
                                          "[Some more captured text:" +
                                          "{0}   Option1" +
                                          "{0}   Option2][Terse text.]",
                                          vbCrLf)
      Dim pattern As String = "\[([^\[\]]+)\]"
      Dim ctr As Integer = 0
      For Each m As Match In Regex.Matches(input, pattern)
         ctr += 1
         Console.WriteLine("{0}: {1}", ctr, m.Groups(1).Value)
      Next
   End Sub
End Module
' The example displays the following output:
'       1: This is captured
'       text.
'       2: This is more captured text.
'       3: Some more captured text:
'          Option1
'          Option2
'       4: Terse text.

正規表現パターン\[([^\[\]]+)\]は次のように定義されています。The regular expression pattern \[([^\[\]]+)\] is defined like this:

パターンPattern 説明Description
\[ 左角かっこと一致します。Match an opening bracket.
([^\[\]]+) 左または右の角かっこではない任意の文字と1回以上一致します。Match any character that is not an opening or a closing bracket one or more times. これが最初のキャプチャ グループです。This is the first capturing group.
\] 右角かっこと一致します。Match a closing bracket.

メソッドはとほぼString.Split同じですが、固定文字セットではなく正規表現パターンに基づいて文字列を分割する点が異なります。 Regex.SplitThe Regex.Split method is almost identical to String.Split, except that it splits a string based on a regular expression pattern instead of a fixed character set. たとえば、次の例では、 Regex.Splitメソッドを使用して、ハイフンとその他の文字のさまざまな組み合わせで区切られた部分文字列を含む文字列を分割しています。For example, the following example uses the Regex.Split method to split a string that contains substrings delimited by various combinations of hyphens and other characters.

String input = "abacus -- alabaster - * - atrium -+- " +
               "any -*- actual - + - armoire - - alarm";
String pattern = @"\s-\s?[+*]?\s?-\s";
String[] elements = System.Text.RegularExpressions.Regex.Split(input, pattern);
foreach (var element in elements)
   Console.WriteLine(element);

// The example displays the following output:
//       abacus
//       alabaster
//       atrium
//       any
//       actual
//       armoire
//       alarm
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim input As String = "abacus -- alabaster - * - atrium -+- " +
                            "any -*- actual - + - armoir - - alarm"
      Dim pattern As String = "\s-\s?[+*]?\s?-\s"
      Dim elements() As String = Regex.Split(input, pattern)
      For Each element In elements
         Console.WriteLine(element)
      Next
   End Sub
End Module
' The example displays the following output:
'       abacus
'       alabaster
'       atrium
'       any
'       actual
'       armoir
'       alarm

正規表現パターン\s-\s?[+*]?\s?-\sは次のように定義されています。The regular expression pattern \s-\s?[+*]?\s?-\s is defined like this:

パターンPattern 説明Description
\s- 空白文字の後にハイフンが続くパターンに一致します。Match a white-space character followed by a hyphen.
\s? 0 個または 1 個の空白文字と一致します。Match zero or one white-space character.
[+*]? + または * のいずれかの文字の0回または1回の繰り返しに一致します。Match zero or one occurrence of either the + or * character.
\s? 0 個または 1 個の空白文字と一致します。Match zero or one white-space character.
-\s ハイフンの後に空白文字が続くパターンに一致します。Match a hyphen followed by a white-space character.

検索メソッドと Substring メソッドSearch methods and the Substring method

文字列内のすべての部分文字列に関心がない場合は、一致を開始する位置のインデックスを返す文字列比較メソッドのいずれかを使用することをお勧めします。If you aren't interested in all of the substrings in a string, you might prefer to work with one of the string comparison methods that returns the index at which the match begins. その後、 Substringメソッドを呼び出して、必要な部分文字列を抽出できます。You can then call the Substring method to extract the substring that you want. 文字列比較のメソッドは次のとおりです。The string comparison methods include:

  • IndexOf。文字列インスタンス内で文字または文字列が最初に出現する位置の0から始まるインデックスを返します。IndexOf, which returns the zero-based index of the first occurrence of a character or string in a string instance.

  • IndexOfAny。文字配列内の任意の文字が最初に出現する位置の、現在の文字列インスタンス内の0から始まるインデックスを返します。IndexOfAny, which returns the zero-based index in the current string instance of the first occurrence of any character in a character array.

  • LastIndexOf。文字列インスタンス内で文字または文字列が最後に出現する位置の0から始まるインデックスを返します。LastIndexOf, which returns the zero-based index of the last occurrence of a character or string in a string instance.

  • LastIndexOfAny。文字配列内の文字が最後に出現する位置の、現在の文字列インスタンス内の0から始まるインデックスを返します。LastIndexOfAny, which returns a zero-based index in the current string instance of the last occurrence of any character in a character array.

次の例ではIndexOf 、メソッドを使用して、文字列内の期間を検索します。The following example uses the IndexOf method to find the periods in a string. 次に、 Substringメソッドを使用して完全な文を返します。It then uses the Substring method to return full sentences.

String value = "This is the first sentence in a string. " +
               "More sentences will follow. For example, " +
               "this is the third sentence. This is the " +
               "fourth. And this is the fifth and final " +
               "sentence.";
var sentences = new List<String>();
int position = 0;
int start = 0;
// Extract sentences from the string.
do 
{
   position = value.IndexOf('.', start);
   if (position >= 0) 
   {
      sentences.Add(value.Substring(start, position - start + 1).Trim());
      start = position + 1;
   }
} while (position > 0);

// Display the sentences.
foreach (var sentence in sentences)
   Console.WriteLine(sentence);

// The example displays the following output:
//       This is the first sentence in a string.
//       More sentences will follow.
//       For example, this is the third sentence.
//       This is the fourth.
//       And this is the fifth and final sentence.
Imports System.Collections.Generic

Module Example
   Public Sub Main()
      Dim value As String = "This is the first sentence in a string. " +
                            "More sentences will follow. For example, " +
                            "this is the third sentence. This is the " +
                            "fourth. And this is the fifth and final " +
                            "sentence."
      Dim sentences As New List(Of String)
      Dim position As Integer = 0
      Dim start As Integer = 0
      ' Extract sentences from the string.
      Do
         position = value.IndexOf("."c, start)
         If position >= 0 Then
            sentences.Add(value.Substring(start, position - start + 1).Trim())
            start = position + 1
         End If
      Loop While position > 0
      
      ' Display the sentences.
      For Each sentence In sentences
         Console.WriteLine(sentence)
      Next
   End Sub
End Module
' The example displays the following output:
'       This is the first sentence in a string.
'       More sentences will follow.
'       For example, this is the third sentence.
'       This is the fourth.
'       And this is the fifth and final sentence.

Split(Char[], Int32, StringSplitOptions) Split(Char[], Int32, StringSplitOptions) Split(Char[], Int32, StringSplitOptions) Split(Char[], Int32, StringSplitOptions)

配列内の文字に基づいて文字列を最大数の部分文字列に分割します。Splits a string into a maximum number of substrings based on the characters in an array.

public:
 cli::array <System::String ^> ^ Split(cli::array <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[]
Public Function Split (separator As Char(), count As Integer, options As StringSplitOptions) As String()

パラメーター

separator
Char[]

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

count
Int32 Int32 Int32 Int32

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

options
StringSplitOptions StringSplitOptions StringSplitOptions StringSplitOptions

返される配列から空の配列要素を省略する場合は RemoveEmptyEntries。返される配列に空の配列要素も含める場合は NoneRemoveEmptyEntries to omit empty array elements from the array returned; or None to include empty array elements in the array returned.

戻り値

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() 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 \"{0}\".", s1);
Console.WriteLine("The delimiter character is '{0}'.\n", 
                   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:\n");

// Display the original string and delimiter string.
Console.WriteLine("2a) The original string is \"{0}\".", s2);
Console.WriteLine("The delimiter string is \"{0}\".\n", 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);

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

/*
This example produces the following results:

1) Split a string delimited by characters:

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

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

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

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

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

2) Split a string delimited by another string:

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

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

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

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

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

*/

' This example demonstrates the String() methods that use
' the StringSplitOptions enumeration.
Class Sample
    Public Shared Sub Main() 
        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
End Class
'
'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の文字が含まれていない場合、 countまたはパラメーターが1の場合、返される配列は、このインスタンスを格納する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. パラメーターがでnullあるか、文字を含んでいない場合は、空白文字が区切り記号と見なされます。 separatorIf the separator parameter is null or contains no characters, white-space characters are assumed to be the delimiters. 空白文字は、Unicode 標準によって定義されtrueChar.IsWhiteSpaceメソッドに渡される場合はを返します。White-space characters are defined by the Unicode standard and return true if they are passed to the Char.IsWhiteSpace method. ただし、このメソッドseparatorオーバーロードの呼び出しのパラメーターがの場合、 nullコンパイラのオーバーロードの解決は失敗します。However, if the separator parameter in the call to this method overload is null, compiler overload resolution fails. 呼び出されたメソッドを明確に識別するには、コードが null の型を示す必要があります。To unambiguously identify the called method, your code must indicate the type of the null. 次の例は、このオーバーロードを明確に識別するいくつかの方法を示しています。The following example shows several ways to unambiguously identify this overload.

string phrase = "The quick  brown fox";
string[] words;

words = phrase.Split(default(Char[]), 3, StringSplitOptions.RemoveEmptyEntries);

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

words = 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)

パラメーターがゼロの場合、 optionsまたはパラメーターがRemoveEmptyEntriesで、このインスタンスの長さが0の場合は、空の配列が返されます。 countIf 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. パラメーターがNoneであり、2つの区切り記号が隣接している場合、またはこのインスタンスの先頭または末尾に区切り記号Emptyがある場合、対応する配列要素にはが含まれます。 optionsIf 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文字が最後の戻り値の要素。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[])文字がnull含まれseparatorていない、または文字を含んでいないが渡された場合、メソッドは、 Trim(Char[])少し異なる文字のセットを使用して、文字列を分割します。文字列をトリミングします。In the .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 characters to split the string than the Trim(Char[]) method does to trim the string. .NET Framework 4 以降では、両方のメソッドで同じセットの Unicode 空白文字が使用されます。Starting with the .NET Framework 4, both methods use an identical set of Unicode white-space characters.

Split(Char, Int32, StringSplitOptions) Split(Char, Int32, StringSplitOptions) Split(Char, Int32, StringSplitOptions)

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 Char Char Char

戻り値

String[]

Split(String[], Int32, StringSplitOptions) Split(String[], Int32, StringSplitOptions) Split(String[], Int32, StringSplitOptions) Split(String[], Int32, StringSplitOptions)

配列内の文字列に基づいて文字列を最大数の部分文字列に分割します。Splits a string into a maximum number of substrings based on the strings in an array. 部分文字列が空の配列の要素を含めるかどうかを指定することができます。You can specify whether the substrings include empty array elements.

public:
 cli::array <System::String ^> ^ Split(cli::array <System::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[]
Public Function Split (separator As String(), count As Integer, options As StringSplitOptions) As String()

パラメーター

separator
String[]

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

count
Int32 Int32 Int32 Int32

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

options
StringSplitOptions StringSplitOptions StringSplitOptions StringSplitOptions

返される配列から空の配列要素を省略する場合は RemoveEmptyEntries。返される配列に空の配列要素も含める場合は NoneRemoveEmptyEntries to omit empty array elements from the array returned; or None to include empty array elements in the array returned.

戻り値

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.

次の例では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() 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 \"{0}\".", s1);
Console.WriteLine("The delimiter character is '{0}'.\n", 
                   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:\n");

// Display the original string and delimiter string.
Console.WriteLine("2a) The original string is \"{0}\".", s2);
Console.WriteLine("The delimiter string is \"{0}\".\n", 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);

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

/*
This example produces the following results:

1) Split a string delimited by characters:

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

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

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

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

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

2) Split a string delimited by another string:

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

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

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

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

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

*/

' This example demonstrates the String() methods that use
' the StringSplitOptions enumeration.
Class Sample
    Public Shared Sub Main() 
        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
End Class
'
'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]>
'

注釈

戻り値の詳細Return value details

区切り記号文字列は、返される配列の要素には含まれません。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. パラメーターがでnullあるか、文字を含んでいない場合は、空白文字が区切り記号と見なされます。 separatorIf the separator parameter is null or contains no characters, white-space characters are assumed to be the delimiters. 空白文字は、Unicode 標準によって定義されtrueChar.IsWhiteSpaceメソッドに渡される場合はを返します。White-space characters are defined by the Unicode standard and return true if they are passed to the Char.IsWhiteSpace method. ただし、このメソッドseparatorオーバーロードの呼び出しのパラメーターがの場合、 nullコンパイラのオーバーロードの解決は失敗します。However, if the separator parameter in the call to this method overload is null, compiler overload resolution fails. 呼び出されたメソッドを明確に識別するにはnull、コードでの型を指定する必要があります。To unambiguously identify the called method, your code must indicate the type of the null. 次の例は、このオーバーロードを明確に識別するいくつかの方法を示しています。The following example shows several ways to unambiguously identify this overload.

string phrase = "The quick  brown fox";
string[] words;

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

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

words = 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)

パラメーターがゼロの場合、 optionsまたはパラメーターがRemoveEmptyEntriesで、このインスタンスの長さが0の場合は、空の配列が返されます。 countIf 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. パラメーターがNoneであり、2つの区切り記号が隣接している場合、またはこのインスタンスの先頭または末尾に区切り記号Emptyがある場合、対応する配列要素にはが含まれます。 optionsIf 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文字が最後の戻り値の要素。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は、 separatorパラメーター内の1つ以上の文字列で区切られたこの文字列の部分文字列を抽出し、それらの部分文字列を配列の要素として返します。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.CompareOptions 、列挙体を参照してください。For more information about word, string, and ordinal sorts, see the System.Globalization.CompareOptions enumeration.

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

separator文字列に共通の文字が含まれている場合にSplitあいまいな結果を避けるために、メソッドはインスタンスの値の最初から最後まで処理を進めseparator 、は、内の区切り記号と等しいの最初の要素と一致します。instance.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[])文字がnull含まれseparatorていない、または文字を含んでいないが渡された場合、メソッドは、 Trim(Char[])少し異なる文字のセットを使用して、文字列を分割します。文字列をトリミングします。In the .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 characters to split the string than the Trim(Char[]) method does to trim the string. .NET Framework 4 以降では、両方のメソッドで同じセットの Unicode 空白文字が使用されます。Starting with the .NET Framework 4, both methods use an identical set of Unicode white-space characters.

Split(String[], StringSplitOptions) Split(String[], StringSplitOptions) Split(String[], StringSplitOptions) Split(String[], StringSplitOptions)

配列内の文字列に基づいて文字列を部分文字列に分割します。Splits a string into substrings based on the strings in an array. 部分文字列が空の配列の要素を含めるかどうかを指定することができます。You can specify whether the substrings include empty array elements.

public:
 cli::array <System::String ^> ^ Split(cli::array <System::String ^> ^ separator, StringSplitOptions options);
[System.Runtime.InteropServices.ComVisible(false)]
public string[] Split (string[] separator, StringSplitOptions options);
member this.Split : string[] * StringSplitOptions -> string[]
Public Function Split (separator As String(), options As StringSplitOptions) As String()

パラメーター

separator
String[]

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

options
StringSplitOptions StringSplitOptions StringSplitOptions StringSplitOptions

返される配列から空の配列要素を省略する場合は RemoveEmptyEntries。返される配列に空の配列要素も含める場合は NoneRemoveEmptyEntries to omit empty array elements from the array returned; or None to include empty array elements in the array returned.

戻り値

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   \"{0}\".", source);
Console.WriteLine();
Console.WriteLine("Using the delimiter string:\n   \"{0}\"", 
                  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("   ");
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 ({0} elements):", 
                  result.Length);
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'
Module Example
   Public Sub Main()
      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()
   End Sub
End Module
' 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
Module Example
   Public Sub Main()
      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
End Module
' 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.

戻り値の詳細Return value details

区切り記号文字列は、返される配列の要素には含まれません。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. 引数がNoneであり、2つの区切り記号が隣接している場合、またはこのインスタンスの先頭または末尾に区切り記号String.Emptyがある場合、対応する配列要素にはが含まれます。 optionsIf 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 sting 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." }.}.

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

このメソッドオーバーロードの呼び出しのnullパラメーターがの場合、コンパイラのオーバーロードの解決は失敗します。separatorIf the separator parameter in the call to this method overload is null, compiler overload resolution fails. 呼び出されたメソッドを明確に識別するにはnull、コードでの型を指定する必要があります。To unambiguously identify the called method, your code must indicate the type of the null. 次の例は、このオーバーロードを明確に識別するいくつかの方法を示しています。The following example shows several ways to unambiguously identify this overload.

string phrase = "The quick  brown fox";
string[] words;

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

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

words = 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は、 separatorパラメーター内の1つ以上の文字列で区切られたこの文字列の部分文字列を抽出し、それらの部分文字列を配列の要素として返します。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.CompareOptions 、列挙体を参照してください。For more information about word, string, and ordinal sorts, see the System.Globalization.CompareOptions enumeration.

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

separator文字列に共通の文字が含まれている場合にSplitあいまいな結果を避けるために、操作は最初からインスタンスの値の末尾まで進み、のseparator最初の要素と一致します。これは、instance.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[])文字がnull含まれseparatorていない、または文字を含んでいないが渡された場合、メソッドは、 Trim(Char[])少し異なる文字のセットを使用して、文字列を分割します。文字列をトリミングします。In the .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 characters to split the string than the Trim(Char[]) method does to trim the string. .NET Framework 4 以降では、両方のメソッドで同じセットの Unicode 空白文字が使用されます。Starting with the .NET Framework 4, both methods use an identical set of Unicode white-space characters.

Split(String, Int32, StringSplitOptions) Split(String, Int32, StringSplitOptions) Split(String, Int32, StringSplitOptions)

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()

パラメーター

戻り値

String[]

Split(Char[], StringSplitOptions) Split(Char[], StringSplitOptions) Split(Char[], StringSplitOptions) Split(Char[], StringSplitOptions)

配列内の文字に基づいて文字列を部分文字列に分割します。Splits a string into substrings based on the characters in an array. 部分文字列が空の配列の要素を含めるかどうかを指定することができます。You can specify whether the substrings include empty array elements.

public:
 cli::array <System::String ^> ^ Split(cli::array <char> ^ separator, StringSplitOptions options);
[System.Runtime.InteropServices.ComVisible(false)]
public string[] Split (char[] separator, StringSplitOptions options);
member this.Split : char[] * StringSplitOptions -> string[]
Public Function Split (separator As Char(), options As StringSplitOptions) As String()

パラメーター

separator
Char[]

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

options
StringSplitOptions StringSplitOptions StringSplitOptions StringSplitOptions

返される配列から空の配列要素を省略する場合は RemoveEmptyEntries。返される配列に空の配列要素も含める場合は NoneRemoveEmptyEntries to omit empty array elements from the array returned; or None to include empty array elements in the array returned.

戻り値

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() 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 \"{0}\".", s1);
Console.WriteLine("The delimiter character is '{0}'.\n", 
                   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:\n");

// Display the original string and delimiter string.
Console.WriteLine("2a) The original string is \"{0}\".", s2);
Console.WriteLine("The delimiter string is \"{0}\".\n", 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);

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

/*
This example produces the following results:

1) Split a string delimited by characters:

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

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

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

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

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

2) Split a string delimited by another string:

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

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

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

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

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

*/

' This example demonstrates the String() methods that use
' the StringSplitOptions enumeration.
Class Sample
    Public Shared Sub Main() 
        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
End Class
'
'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]>
'

注釈

戻り値の詳細Return value details

区切り文字 ( 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. 引数がNoneであり、2つの区切り記号が隣接している場合、またはこのインスタンスの先頭または末尾に区切り記号String.Emptyがある場合、対応する配列要素にはが含まれます。 optionsIf 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

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

このメソッドオーバーロードの呼び出しのnullパラメーターがの場合、コンパイラのオーバーロードの解決は失敗します。separatorIf the separator parameter in the call to this method overload is null, compiler overload resolution fails. 呼び出されたメソッドを明確に識別するにはnull、コードでの型を指定する必要があります。To unambiguously identify the called method, your code must indicate the type of the null. 次の例は、このオーバーロードを明確に識別するいくつかの方法を示しています。The following example shows several ways to unambiguously identify this overload.

string phrase = "The quick  brown fox";
string[] words;

words = phrase.Split(default(Char[]), StringSplitOptions.RemoveEmptyEntries);

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

words = 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は、 separatorパラメーターの1つ以上の文字で区切られたこの文字列の部分文字列を抽出し、それらの部分文字列を配列の要素として返します。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.CompareOptions 、列挙体を参照してください。For 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[])文字がnull含まれseparatorていない、または文字を含んでいないが渡された場合、メソッドは、 Trim(Char[])少し異なる文字のセットを使用して、文字列を分割します。文字列をトリミングします。In the .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 characters to split the string than the Trim(Char[]) method does to trim the string. .NET Framework 4 以降では、両方のメソッドで同じセットの Unicode 空白文字が使用されます。Starting with the .NET Framework 4, both methods use an identical set of Unicode white-space characters.

Split(Char[], Int32) Split(Char[], Int32) Split(Char[], Int32) Split(Char[], Int32)

配列内の文字に基づいて文字列を最大数の部分文字列に分割します。Splits a string into a maximum number of substrings based on the characters in an array. 返される部分文字列の最大数を指定します。You also specify the maximum number of substrings to return.

public:
 cli::array <System::String ^> ^ Split(cli::array <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[]

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

count
Int32 Int32 Int32 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 、がによって返されるSplit文字列の数にどのように影響するかを示します。The following example demonstrates how count affects the number of strings returned by Split.

string delimStr = " ,.:";
char [] delimiter = delimStr.ToCharArray();
string words = "one two,three:four.";
string [] split = null;

Console.WriteLine("The delimiters are -{0}-", delimStr);
for (int x = 1; x <= 5; x++) 
{
   split = words.Split(delimiter, x);
   Console.WriteLine("\ncount = {0,2} ..............", x);
   foreach (var s in split) 
   {
       Console.WriteLine("-{0}-", s);
   }
}

// The example displays the following output:
//       The delimiters are - ,.:-
//       count =  1 ..............
//       -one two,three:four.-
//       count =  2 ..............
//       -one-
//       -two,three:four.-
//       count =  3 ..............
//       -one-
//       -two-
//       -three:four.-
//       count =  4 ..............
//       -one-
//       -two-
//       -three-
//       -four.-
//       count =  5 ..............
//       -one-
//       -two-
//       -three-
//       -four-
//       --
Public Class StringSplit2
   Public Shared Sub Main()
      
      Dim delimStr As String = " ,.:"
      Dim delimiter As Char() = delimStr.ToCharArray()
      Dim words As String = "one two,three:four."
      Dim split As String() = Nothing
      
      Console.WriteLine("The delimiters are -{0}-", delimStr)
      Dim x As Integer
      For x = 1 To 5
         split = words.Split(delimiter, x)
         Console.WriteLine(ControlChars.Cr + "count = {0,2} ..............", x)
         Dim s As String
         For Each s In  split
            Console.WriteLine("-{0}-", s)
         Next s
      Next x
   End Sub 
End Class 
' The example displays the following output:
'       The delimiters are - ,.:-
'       count =  1 ..............
'       -one two,three:four.-
'       count =  2 ..............
'       -one-
'       -two,three:four.-
'       count =  3 ..............
'       -one-
'       -two-
'       -three:four.-
'       count =  4 ..............
'       -one-
'       -two-
'       -three-
'       -four.-
'       count =  5 ..............
'       -one-
'       -two-
'       -three-
'       -four-
'       --

注釈

区切り文字は、返される配列の要素には含まれません。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.

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

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文字が最後の戻り値の要素。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 following table provides examples.

文字列値String value 区切り記号Separator カウントCount 返された配列Returned array
"42, 12, 19""42, 12, 19" 新しい Char [] {', ', ' '} (C#)new Char[] {',', ' '} (C#)

Char () = {"," c "," c} (Visual Basic)Char() = {","c, " "c} (Visual Basic)
22 {"42", " 12, 19"}{"42", " 12, 19"}
"42..12..19""42..12..19" 新しい Char [] {'}new Char[] {'.'} (C#)(C#)

Char () = {"."c} (Visual Basic)Char() = {"."c} (Visual Basic)
44 {"42", "", "12", ".19"}{"42", "", "12", ".19"}
バナナ"Banana" 新しい Char [] {'}new Char[] {'.'} (C#)(C#)

Char () = {"."c} (Visual Basic)Char() = {"."c} (Visual Basic)
22 {"バナナ"}{"Banana"}
"Darb\nSmarba" (C#)"Darb\nSmarba" (C#)

"Darb" & vbLf & "Smarba" (Visual Basic)"Darb" & vbLf & "Smarba" (Visual Basic)
新しい Char [] {} (C#)new Char[] {} (C#)

Char () = {} (Visual Basic)Char() = {} (Visual Basic)
11 {"Darb\nSmarba"}(C#){"Darb\nSmarba"} (C#)

"Darb" & vbLf & "Smarba" (Visual Basic)"Darb" & vbLf & "Smarba" (Visual Basic)
"Darb\nSmarba" (C#)"Darb\nSmarba" (C#)

"Darb" & vbLf & "Smarba" (Visual Basic)"Darb" & vbLf & "Smarba" (Visual Basic)
new Char [] null (C#)new Char[] null (C#)

Char () = NothingChar() = Nothing
22 {"Darb", "Smarba"}{"Darb", "Smarba"}
"Darb\nSmarba" (C#)"Darb\nSmarba" (C#)

"Darb" & vbLf & "Smarba" (Visual Basic)"Darb" & vbLf & "Smarba" (Visual Basic)
new Char [] null (C#)new Char[] null (C#)

Char () = NothingChar() = Nothing
100100 {"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[])文字がnull含まれseparatorていない、または文字を含んでいないが渡された場合、メソッドは、 Trim(Char[])少し異なる文字のセットを使用して、文字列を分割します。文字列をトリミングします。In the .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 characters to split the string than the Trim(Char[]) method does to trim the string. .NET Framework 4 以降では、両方のメソッドで同じセットの Unicode 空白文字が使用されます。Starting with the .NET Framework 4, both methods use an identical set of Unicode white-space characters.

こちらもご覧ください

Split(Char, StringSplitOptions) Split(Char, StringSplitOptions) Split(Char, StringSplitOptions)

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 Char Char Char

戻り値

String[]

Split(String, StringSplitOptions) Split(String, StringSplitOptions) Split(String, StringSplitOptions)

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()

パラメーター

戻り値

String[]

Split(Char[]) Split(Char[]) Split(Char[]) Split(Char[])

配列内の文字に基づいて文字列を部分文字列に分割します。Splits a string into substrings that are based on the characters in an array.

public:
 cli::array <System::String ^> ^ Split(... cli::array <char> ^ separator);
public string[] Split (params char[] separator);
member this.Split : char[] -> string[]
Public Function Split (ParamArray separator As Char()) As String()

パラメーター

separator
Char[]

この文字列から部分文字列を取り出すために区切り文字として使用する文字配列、区切り文字が含まれていない空の配列、または nullA character array that delimits the substrings in this string, 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.

次の例では、空白と句読点を区切り記号として扱うことによって、テキストのブロックから個々の単語を抽出する方法を示します。The following example demonstrates how to extract individual words from a block of text by treating white space and punctuation marks as delimiters. メソッドのパラメーターseparatorに渡される文字配列は、スペース文字とタブ文字で構成され、いくつかの一般的な区切り記号と共に使用されます。 String.Split(Char[])The character array passed to the separator parameter of the String.Split(Char[]) method consists of a space character and a tab character, together with some common punctuation symbols.

string words = "This is a list of words, with: a bit of punctuation" +
               "\tand a tab character.";

string [] split = words.Split(new Char [] {' ', ',', '.', ':', '\t' });

foreach (string s in split) 
{

    if (s.Trim() != "")
        Console.WriteLine(s);
}

// The example displays the following output to the console:
//       This
//       is
//       a
//       list
//       of
//       words
//       with
//       a
//       bit
//       of
//       punctuation
//       and
//       a
//       tab
//       character
Public Class SplitTest
    Public Shared Sub Main()
        Dim words As String = "This is a list of words, with: a bit of punctuation" + _
                              vbTab + "and a tab character."
        Dim split As String() = words.Split(New [Char]() {" "c, ","c, "."c, ":"c, CChar(vbTab) })
                
        For Each s As String In  split
            If s.Trim() <> "" Then
                Console.WriteLine(s)
            End If
        Next s
    End Sub
End Class
' The example displays the following output to the console:
'       This
'       is
'       a
'       list
'       of
'       words
'       with
'       a
'       bit
'       of
'       punctuation
'       and
'       a
'       tab
'       character

注釈

文字列が既知の文字のセットで区切られている場合は、 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.

戻り値の詳細Return value details

区切り文字は、返される配列の要素には含まれません。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. 次にいくつかの例を示します。Here are some examples:

文字列値String value 区切り記号Separator 返された配列Returned array
"42, 12, 19""42, 12, 19" 新しい Char [] {', ', ' '} (C#)new Char[] {',', ' '} (C#)

Char () = {"," c, "" c}) (Visual Basic)Char() = {","c, " "c}) (Visual Basic)
{"42", "", "12", "", "19"}{"42", "", "12", "", "19"}
"42..12..19""42..12..19" 新しい Char [] {'}new Char[] {'.'} (C#)(C#)

Char () = {"."c} (Visual Basic)Char() = {"."c} (Visual Basic)
{"42", "", "12", "", "19"}{"42", "", "12", "", "19"}
バナナ"Banana" 新しい Char [] {'}new Char[] {'.'} (C#)(C#)

Char () = {"."c} (Visual Basic)Char() = {"."c} (Visual Basic)
{"バナナ"}{"Banana"}
"Darb\nSmarba" (C#)"Darb\nSmarba" (C#)

"Darb" & vbLf & "Smarba" (Visual Basic)"Darb" & vbLf & "Smarba" (Visual Basic)
新しい Char [] {} (C#)new Char[] {} (C#)

Char () = {} (Visual Basic)Char() = {} (Visual Basic)
{"Darb", "Smarba"}{"Darb", "Smarba"}
"Darb\nSmarba" (C#)"Darb\nSmarba" (C#)

"Darb" & vbLf & "Smarba" (Visual Basic)"Darb" & vbLf & "Smarba" (Visual Basic)
null (C#)null (C#)

Nothing (Visual Basic)Nothing (Visual Basic)
{"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 規格で定義されています。メソッドに渡された場合は、を返しtrueます。 Char.IsWhiteSpaceWhite-space characters are defined by the Unicode standard; they return true if they are passed to the Char.IsWhiteSpace method.

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

String.Splitこのオーバーロードの1つのパラメーターは文字配列ですが、次の例に示すように、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.
Module Example
   Public Sub Main()
      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
End Module
' The example displays the following output:
'     Thi
'      i
'      a
'     hort
'     tring.

パラメーターはParamArrayAttribute属性で修飾されているため、コンパイラは1つの文字を単一要素の文字配列として解釈します。 separatorBecause 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[])は、 separator配列内の1つ以上の文字で区切られたこの文字列の部分文字列を抽出し、それらの部分文字列を配列の要素として返します。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.CompareOptions 、列挙体を参照してください。For 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. アプリケーションで最適なパフォーマンスが求められる場合や、アプリケーションでメモリ割り当てを管理する必要IndexOfIndexOfAnyある場合は、メソッドまたはメソッドの使用を検討してください。If 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[])文字がnull含まれseparatorていない、または文字を含んでいないが渡された場合、メソッドは、 Trim(Char[])少し異なる文字のセットを使用して、文字列を分割します。文字列をトリミングします。In the .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 characters to split the string than the Trim(Char[]) method does to trim the string. .NET Framework 4 以降では、両方のメソッドで同じセットの Unicode 空白文字が使用されます。Starting with the .NET Framework 4, both methods use an identical set of Unicode white-space characters.

こちらもご覧ください

適用対象