【C#】StartsWithを複数の文字列対応する

string クラスに StartsWith という特定の文字列で始まるかどうかをチェックできるメソッドがあります。

使い方はこんな感じです。

string str = "aaaabbbbcccc";
if(str.StartsWith("aaa"))  // str が "aaa" から始まるかどうかチェックする
{
    // 一致する
}
else
{
   // 一致しない
}

これによって指定した変数内の文字列が指定した文字列から始まっているかどうかを確認できますがこれを複数の文字列で確認できるように改善したいと思います。

string str = "aaabbbccc";
if(str.StartsWith("aaa", "bbb", "ccc"))
{
    // "aaa", "bbb", "ccc" のいずれかに一致する
}
else
{
    // 一致しない
}

確認環境

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

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

実装コード

以下実装で StartsWith, EndsWith, Contains の3つのメソッドを複数対応します。

// StringExtension.cs

public static class StringExtension
{
    // 指定した複数の文字列のどれかに一致するかどうかを判定する
    // true : 存在する / false : 存在しない
    public static bool Contains(this string self, params string[] words) => Contains(self, false, params string[] words);
    public static bool Contains(this string self, bool ignoreCase, params string[] words)
    {
        for (int i = 0; i < words.Length; i++)
        {
            if (string.Compare(self, words[i], ignoreCase) == 0)
            {
                return true;
            }
        }
        return false;
    }

    // 指定した複数の文字列のいずれかから開始する文字列かどうかを判定します。
    // true : 存在する / false : 存在しない
    public static bool StartsWith(this string self, params string[] words) => StartsWith(self, false, params string[] words);
    public static bool StartsWith(this string self, bool ignoreCase, params string[] words)
    {
        for (int i = 0; i < words.Length; i++)
        {
            if (self.StartsWith(words[i], true, null))
            {
                return true;
            }
        }
        return false;
    }

    // 指定した複数の文字列のいずれかから開始する文字列かどうかを判定します。
    // true : 存在する / false : 存在しない
    public static bool EndsWith(this string self, params string[] words) => EndsWith(self, false, params string[] words);
    public static bool EndsWith(this string self, bool ignoreCase, params string[] words)
    {
        for (int i = 0; i < words.Length; i++)
        {
            if (self.EndsWith(words[i], true, null))
            {
                return true;
            }
        }
        return false;
    }
}