欢迎使用C#或VB.NET建议。
我有以下代码:
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
只要字符串中存在单词,我希望所有这些都返回True。
是否有任何现有的功能覆盖任何情况,无论字符串中的单词位置如何?
答案 0 :(得分:5)
words.Split(' ').Any(someText.Contains)
答案 1 :(得分:4)
someText.Split(' ').Intersect(someWord.Split(' ')).Any();
答案 2 :(得分:1)
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
答案 3 :(得分:1)
Linq解决方案的替代方案是扩展方法:
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;
}
用法:
string test = "stack overflow";
string searchPhrase = "overflow stack";
Console.WriteLine(test.ContainsAllWords(searchPhrase));
更好的可重用性并使您的代码更具说明性(imho)。