7

How would i go about making a function that would return true if a string contains any element of an array?

Something like this:

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

would return true.

1
  • 2
    foreach + String.IndexOf Commented Nov 26, 2012 at 4:19

4 Answers 4

9

You can do it like this:

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 that the element be a full word (i.e. the above fragment would return true, even though the word "fox" is not present there as a single word).

Sign up to request clarification or add additional context in comments.

4 Comments

Or if you don't mind losing a mild amount of efficiency for more readability: if (array.Any(s => myStr.Contains(s)) { will do as well, I believe.
Thanks, this is exactly what i was looking for! Thanks also for fixing my bad formatting Mr_Green :) Also is it easy to change it so that it is case insensitive?
@user1852287 Yes - use myStr.IndexOf(s, StringComparison.OrdinalIgnoreCase) to make it case-insensitive.
Smaller yet: bool b = words.Any(str.Contains);
0

You can split a string and use Enumerable.Intersect. It will be much more efficient for long strings than Any + IndexOf:

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

1 Comment

@user18522877 This assumes you're looking for entire words rather than substrings, so in an example like dasblinkenlight's it will return false - that might be what you're looking for, but if it is then you should probably change your question.
0

No need of looping,here is a faster method :

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

Comments

0

I think you need to check whether a string contains in other string (I dont know about performance)

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.