Question

Is there a variant of this?

if (blabla.Contains("I'm a noob") | blabla.Contains("sry") | blabla.Contains("I'm a noob "+"sry"))
    {
        //stuff
    }

like:

if (blabla.Contains("I'm a noob) and/or ("sry")
    {
        //stuff
    }

Help is appreciated!

Was it helpful?

Solution 2

As far as I'm aware, there are no built-in methods to do this. But with a little LINQ and extension methods, you can create your own methods that will check to see if a string contains any or all tokens:

public static class ExtensionMethods{
    public static bool ContainsAny(this string s, params string[] tokens){
        return tokens.Any(t => s.Contains(t));
    }

    public static bool ContainsAll(this string s, params string[] tokens){
        return tokens.All(t => s.Contains(t));
    }
}

You could use it like this (remember, params arrays take a variable number of parameters, so you're not limited to just two like in my example):

var str = "this is a string";
Console.WriteLine(str.ContainsAny("this", "fake"));
Console.WriteLine(str.ContainsAny("doesn't", "exist"));
Console.WriteLine(str.ContainsAll("this", "is"));
Console.WriteLine(str.ContainsAll("this", "fake"));

Output:

True
False
True
False

Edit:

For the record, LINQ is not necessary. You could just as easily write them this way:

public static class ExtensionMethods{
    public static bool ContainsAny(this string s, params string[] tokens){
        foreach(string token in tokens)
            if(s.Contains(token)) return true;
        return false;
    }

    public static bool ContainsAll(this string s, params string[] tokens){
        foreach(string token in tokens)
            if(!s.Contains(token)) return false;
        return true;
    }
}

OTHER TIPS

You can't collapse it quite as far as you asked, but you can do:

if (blabla.Contains("I'm a noob") || blabla.Contains("sry"))
{
    //stuff
}

The "and" case is handled here because a string with both would actually pass both of the statements in the "Or".

var arr = new[]{"I'm a noob" ,"sry", "I'm a noob +sry"};
if(arr.Any(x => blabla.Contains(x)))
{

}

You can use a regex:

Regex r = new Regex("I'm a noob|sry|I'm a noob sry");
if(r.IsMatch(blabla)) {
    //TODO: do something
}

Regular expressions have other advanced features like: a* matches with the empty string, a, aa, aaa,...

The funny part is that if you "compile" the regex (for instance using new Regex("I'm a noob|sry|I'm a noob sry",RegexOptions.Compiled), C# will turn it automatically into the fastest solution mechanism possible. For instance if blabla is a 100k chars string, you will only run once over the entire string. And for instance redundant parts like I'm a noob sry will be omitted automatically.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top