【C#】文字列を分割するSplitメソッドをより使いやすいよう改善する

C# である文字列を特定の文字で複数の文字列に分割する Split メソッドの利用性を向上するための拡張メソッドの紹介です。

はじめに

Split メソッドっは大変便利ですがセパレーターに複数の文字を指定する場合や、文字列をセパレーターとして使う場合以下のように配列を宣言しないといけません。

string str = "a b c,d";

// 複数の区切り文字をしていする場合配列を用意しないといけない
str.Split(new char[] { ' ', '\t', '\n' }, StringSplitOptions.RemoveEmptyEntries);

// 複数の文字列をセパレーターとして使う場合配列を用意しないといけない
str.Split(new string[] { "\n", "\r\n" });

これだと少し面倒なので以下のように配列宣言が不要な拡張メソッドを作成したいと思います。

string str = "a b c,d";

// 配列宣言不要に変更
str.Split(StringSplitOptions.RemoveEmptyEntries, ' ', '\t', '\n');

// 配列宣言不要に変更
str.Split("\n", "\r\n" );

確認環境

この記事の動作確認環境は以下の通りです。

  • C# 8.0
  • .NET Core 3.1
  • VisualStudio 2019
  • Windows10

コンソールプログラムで動作を確認

実装コード

上記使用方法に合うように可変引数が指定できるようにパラメーターの順序を調整します。

C#の言語仕様上可変引数はメソッドの引数の順序の最後にしか指定できない制限があるためです。

以下をコードに追加すると冒頭のように配列宣言が不要になります。.NET 標準ライブラリのパラメーターの増え方の規則を無視して可変引数を引数の最後に移動しています。

public static class StringExtension
{
    public static string[] Split(this string self, int count, params char[] separator)
    {
        return self.Split(separator, count);
    }
    public static string[] Split(this string self, StringSplitOptions oprtions, params char[] separator)
    {
        return self.Split(separator, oprtions);
    }
    public static string[] Split(this string self, params string[] separator)
    {
        return self.Split(separator);
    }
    public static string[] Split(this string self, int count, 
        StringSplitOptions oprtions, params char[] separator)
    {
        return self.Split(separator, count, oprtions);
    }
    public static string[] Split(this string self, StringSplitOptions options, params string[] separator)
    {
        return self.Split(separator, options);
    }
    public static string[] Split(this string self, int count, 
        StringSplitOptions options, params string[] separator)
    {
        return self.Split(separator, count, options);
    }
}