Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a String contains any of some strings

Well, there's always this:

public static bool ContainsAny(this string haystack, params string[] needles)
{
    foreach (string needle in needles)
    {
        if (haystack.Contains(needle))
            return true;
    }

    return false;
}

Usage:

bool anyLuck = s.ContainsAny("a", "b", "c");

Nothing's going to match the performance of your chain of || comparisons, however.


Here's a LINQ solution which is virtually the same but more scalable:

new[] { "a", "b", "c" }.Any(c => s.Contains(c))

var values = new [] {"abc", "def", "ghj"};
var str = "abcedasdkljre";
values.Any(str.Contains);

If you are looking for single characters, you can use String.IndexOfAny().

If you want arbitrary strings, then I'm not aware of a .NET method to achieve that "directly", although a regular expression would work.