C # Contains a few words not together

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

This code checks if "Word1" and "Word2" are in a string together, for example. nothing in between, but how to check if a string contains these two words regardless of order or any other words between them?

eg. Returns true if string

  Word1Word2 

Returns false

  Word1 Text Word2 
+6
source share
3 answers

Just make sure every word is in r .

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

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

Edit:

As @Alexei Levenkov (+1) notes, it can be found using the IndexOf method.

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

Make sure that each word is contained in a line:

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

If you do this often, you can improve readability (IMO) and brevity by creating an extension method:

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

Used as:

 "Word1 Text Word2".ContainsAll("Word1", "Word2") // true 
+5
source

To do this, you can use the && operator:

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

Please note that this will verify that both words are in any order. If you need to make sure that the first word precedes the second, get the indices of each word and check that the index of the first word is lower than the index of the second:

 var ind1 = r.IndexOf("Word1"); var ind2 = r.IndexOf("Word2"); if (ind1 >= 0 && ind2 > ind1) { ... } 
+4
source

Source: https://habr.com/ru/post/950376/


All Articles