c# Contains multiple words not together

23,496

Solution 1

Just verify that each word is contained on r.

if (r.Contains("Word1") && r.Contains("Word2"))

This code checks for the existence of "Word1" AND "Word2" inside the original string, regardless its relative position inside the string.

Edit:

As @Alexei Levenkov (+1) note on his comment, the same solution can be reached using IndexOf method.

if (r.IndexOf("Word1", StringComparison.InvariantCultureIgnoreCase) > -1 
    && r.IndexOf("Word2", StringComparison.InvariantCultureIgnoreCase) > -1))

Solution 2

Check that each word is contained within the string:

if (r.Contains("Word1") && r.Contains("Word2")))

If this is something you do often, you can improve readability (IMO) and conciseness by making an extension method:

public static bool ContainsAll(this string source, params string[] values)
{
    return values.All(x => source.Contains(x));
}

Used like:

"Word1 Text Word2".ContainsAll("Word1", "Word2") // true

Solution 3

You can use an && operator for that:

if (r.Contains("Word1") &&  r.Contains("Word2"))

Note that this would check that both words are there in any order. If you must ensure that the first word precedes the second, get indexes of each word, and check that the index of the first word is lower than the index of the second one:

var ind1 = r.IndexOf("Word1");
var ind2 = r.IndexOf("Word2");
if (ind1 >= 0 && ind2 > ind1) {
    ...
}
Share:
23,496
First Second
Author by

First Second

Updated on July 23, 2022

Comments

  • First Second
    First Second almost 2 years
       if (r.Contains("Word1" + "Word2"))
    

    This code checks if "Word1" and "Word2" are in the string together e.g. nothing in between them but how does one check if the string contains those two words regardless of order or any other words in between them?

    e.g. Returns true if string is

        Word1Word2
    

    Returns false

        Word1 Text Word2