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
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))
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With