C # string and array comparison

How can I make a function that returns true if the string contains any element of the array?

Something like that:

 string str = "hi how are you"; string[] words = {"hi", "hey", "hello"}; 

will return true .

+7
source share
4 answers

You can do it as follows:

 var array = new[] {"quick", "brown", "fox"}; var myString = "I love foxes."; if (array.Any(s => myStr.IndexOf(s) >= 0)) { // One of the elements is there } 

This approach does not require the element to be a complete word (i.e. the above snippet would return true even if the word "fox" not there as one word).

+9
source

You can split the string and use Enumerable.Intersect . This will be much more efficient for long lines than Any + IndexOf :

 var any = words.Intersect(str.Split()).Any(); 
0
source

There is no need for a loop, here is a faster method:

  string [] arr = {"One","Two","Three"}; var target = "One"; var results = Array.FindAll(arr, s => s.Equals(target)); 
0
source

I think you need to check if the string contains in another string (I don't know about performance)

 foreach(string strLine in words) { if(strLine.Contains(str)) //or str.Contains(strLine) { return true; } } //return false; 
0
source

All Articles