C#のSplit機能にはどんな機能がありますか?
C#のsplitメソッドは特定の区切り文字で文字列を複数のサブ文字列に分割する機能です。一般的な使い方は次の通りです:
- 指定した区切り文字で文字列を分割し、文字列配列に変換します。
- 複数の区切り文字を指定するか、区切り文字として文字列配列を使用することができます。
- 拆分回数を指定することができ、拆分回数を制限することができます。
- 空白文字を無視して分割するように指定できます。
- 空文字列を維持するかどうかを制御するには、StringSplitOptions列挙型を使用できます。
以下はコードの例です。
string sentence = "Hello,world";
string[] words = sentence.Split(',');
// words = {"Hello", "world"}
string sentence2 = "apple,banana;orange";
string[] words2 = sentence2.Split(new char[] { ',', ';' });
// words2 = {"apple", "banana", "orange"}
string sentence3 = "one two three four five";
string[] words3 = sentence3.Split(new char[] { ' ' }, 3);
// words3 = {"one", "two", "three four five"}
string sentence4 = "apple, ,banana, ,orange";
string[] words4 = sentence4.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
// words4 = {"apple", "banana", "orange"}