欢迎 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,只要字符串中存在单词。
是否有任何现有函数可以涵盖任何情况,而不管字符串中的单词位置如何?
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
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));
更好地实现可重用性,并使代码更具声明性(恕我直言)。