C# or VB.NET suggestion are welcome.
I have the following code:
Dim someText = "Stack Over Flow Community"
Dim someWord = "Over Community"
If someText.Contains(someWord) Then
Response.Write("Word found.")
Else
Response.Write("No word found.")
End If
Function Contains looks only for next words from left to right.
someText.Contains("Over Stack") returns False
someText.Contains("Stack Community") returns False
I want all of these to return True as long as there are words that exist in t开发者_开发技巧he string.
Is there any existing function that cover any case regardless of words position in the string?
words.Split(' ').Any(someText.Contains)
someText.Split(' ').Intersect(someWord.Split(' ')).Any();
public static class StringExtension
{
public static bool ContainsWord(this string source, string contain)
{
List<string> sourceList = source.Split(' ').ToList();
List<string> containList = contain.Split(' ').ToList();
return sourceList.Intersect(containList).Any();
}
}
string someText = "Stack Over Flow Community";
var res = someText.ContainsWord("Over Stack"); // return true
var res1 = someText.ContainsWord("Stack Community"); // return true
var res2 = someText.ContainsWord("Stack1 Community"); // return false
An alternative to the Linq solutions would be an extension method:
public static bool ContainsAllWords(this string input, string search)
{
foreach (string word in search.split(' ', StringSplitOptions.RemoveEmptyEntries))
{
if (!input.Contains(word))
return false;
}
return true;
}
Usage:
string test = "stack overflow";
string searchPhrase = "overflow stack";
Console.WriteLine(test.ContainsAllWords(searchPhrase));
Better for re-usability and makes your code more declarative (imho).
精彩评论