将字符串与单词列表进行比较

Comparing a String to a List of Words

我正在尝试在我正在编写的程序中实现搜索功能。目前,我有一个正在搜索的字符串列表。

我想做的是检查是否所有个输入搜索框的单词出现在搜索结果中。然而,要注意的是它们可以以任何顺序出现。例如,如果字符串是:

The quick brown fox jumps over the lazy dog

我要输入:

dog fox brown

它会 return 正匹配。

我的第一个想法是.split把搜索框里的词做成一个数组。然后,遍历字符串列表,检查字符串是否包含数组中的每个单词,否则,将其从列表中删除。迭代完所有字符串后,显示结果。

但是,我可以想象会有大量开销,特别是因为我希望实时完成过滤,即。附加到文本框的 TextChanged 事件。

是否有更有效的过滤方法?在我开始编码之前,我只是想确保没有更有效的方法来做到这一点。

我在 Linq .Select().Sum()

中提议 Regex.Matches().Count

给定提供的输入字符串:

The quick brown fox jumps over the lazy dog

计算该字符串中匹配的模式数和模式(单词)数。

给定字符串中包含的模式:(并假设分隔符是 chr(32)

dog fox brown

Imports System.Text.RegularExpressions

Dim words As Integer
Dim NumberOfMatches As Integer = GetMatchingWords(
                                 "The quick brown fox jumps over the lazy dog",
                                 "dog fox brown",
                                 words)


Public Function GetMatchingWords(TextToSearch As String, WordsToMatch As String, ByRef words As Integer) As Integer

    words = Regex.Matches(WordsToMatch, ChrW(32)).Count + 1
    Return WordsToMatch.Split(ChrW(32)).Select(
           Function(word) Regex.Matches(TextToSearch, word).Cast(Of Match)().Count()).Sum()
End Function

这个函数returns:

words = 3
NumberOfMatches = 3<br>