Search code examples
c#arraysstring-search

Look for part of a string in an array?


i'm looking for an efficient way to look for certain words, would i use switch/case, int/string.IndexOf('!'); foreach loop/contains?

i have a string that i'm receiving from a client. so, let's say i get:

string x = "fjdswordslkjf?dkHEYw";

i have an array of possible values that correspond with that message. (none of this is syntactically correct, just so you get an idea):

someArray[0]= "?";
someArray[1]= "HEY";
someArray[2]= "find.me";

basically i want to know

 if (x contains someWordinSomeArray)

i want to search through the string x, using the words in the array. what would be the most efficient way to do this in c#? i just need a bool response, not the exact location in the string.

ANSWER

here's what i used:

foreach (string searchstring in valuesArray)
        {
            indx = test.IndexOf(searchstring);
            if (indx > -1)
            {
                testValue = true;
                break;
            }             
        }

Solution

  • Loop through the array, and exit as soon as you find a match:

    bool found = someArray.Any(s => x.Contains(s));
    

    A non-LINQ version of the same would be:

    bool found = false;
    foreach (string s in someArray) {
      if (x.Contains(s)) {
        found = true;
        break; // exit from loop
      }
    }