Look for part of a string in an array?
-
20-03-2021 - |
Question
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
}
}
OTHER TIPS
You can use the appropriate extension method depending on exactly you want. Suppose that the input string is stored in s
, and that the array of words you want to check is wordsToMatch
. Then:
... if you want to know whether any of the words match:
var stringMatched = wordsToMatch.Any(w => s.Contains(w));
// true or false
... if you want to know which words match:
var matchingWords = wordsToMatch.Where(w => s.Contains(w));
// ["apple", "ban", "banana", "nana", "coconut", "nut", ...]
... if you want to know whether each word matches:
var wordMatchResult = wordsToMatch.Select(w => s.Contains(w));
// [true, true, false, true, false, true, ...]
The .NET framework has a string.contains method that does what you want to do. Loop through the array. For each item in the array, check if x.Contains(item) is true
http://msdn.microsoft.com/en-us/library/dy85x1sa.aspx
string s1 = "fjdswordslkjf?dkHEYw";
foreach (String s in array)
b = s1.Contains(Array[item]); //will be T or F
bool CheckForString(string[] someArray,string x)
{
foreach(string s in someArray)
if(x.contains(s))
return true;
return false;
}
I think "contains" is faster than indexOf()