Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# Contains multiple words not together

Tags:

c#

contains

   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
like image 397
First Second Avatar asked Jul 26 '13 16:07

First Second


2 Answers

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))
like image 154
HuorSwords Avatar answered Oct 23 '22 19:10

HuorSwords


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
like image 10
Tim S. Avatar answered Oct 23 '22 19:10

Tim S.