如何检查一个字符串中的每个单词是否在另一个字符串中找到?
比方说,我有一本书的标题,我在数据库中搜索它。数据库产生匹配,其中一些是完全匹配的,其中一些是部分匹配的。如何检查一个字符串中的每个单词是否在另一个字符串中找到?
A full match
是当搜索结果中的每个单词由搜索项中的单词表示时。(i.e. there does not have to be a complete overlap on both sides)
我只关心找到完整匹配。
所以,如果我为"Ernest Hemingway - The Old Man and the Sea"
键入搜索,并将结果返回如下:
Charles Nordhoff - Men Against The Sea
Rodman Philbrick - The Young Man and the Sea
Ernest Hemingway - The Old Man and the Sea
Ernest Hemingway - The Sun Also Rises
Ernest Hemingway - A Farewell to Arms
Ernest Hemingway - For Whom the Bell Tolls
Ernest Hemingway - A Moveable Feast
Ernest Hemingway - True at First Light
Men Against The Sea
The Old Man and the Sea
The Old Man and the Sea Dog
有在此列表中有两个full matches
:(根据上述定义)
Ernest Hemingway - The Old Man and the Sea
The Old Man and the Sea
在Java中这样做,假设我有两个变量:
String searchTerms;
List<String> searchResults;
在例如searchTerms
上述代表着什么我输入:Ernest Hemingway - The Old Man and the Sea
searchResults
代表字符串我从上面的数据库返回的名单。
for (String result : searchResults) {
// How to check for a full match?
// (each word in `result` is found in `searchTerms`
}
我的问题是:在这个for-loop
,我如何检查在result
字符串的每一个字是否有在searchTerms
字符串对应词?
假设你的数据库的结果是准确的,
分裂result
成标记(字)使用String.split(String delimiter)
并查看每个令牌是否在searchTerms
发现(使用searchTerms.indexOf(String word) == -1
)。
for (String result : searchResults) {
for(String word : result) {
if(searchTerms.indexOf(word) == -1) {
// result is not a full match
}
}
//If none of the if statements executed, statement is a full match.
}
要查找完全匹配,就像您定义它的那样,您要测试一组标记是否包含特定的子集。您可以使用Set轻松完成此操作,您可以在收集库中免费获得这些信息。要做到这一点是(正则表达式的一边为代价)的一种方法:
Set<String> searchTerms = new HashSet<String>();
Set<String> resultTokens = new HashSet<String>();
searchTerms.addAll(Arrays.asList(searchString.split("\\s+"));
for (String result : searchResults)
{
resultTokens.clear();
resultTokens.addAll(Arrays.asList(result.split("\\s+")));
if (resultTokens.containsAll(searchTerms))
{
// Perform match code
}
}
另外,如果你想成为它严格,你可以使用resultTokens.equals(searchTerms)测试集相等。在你的例子中,这将缩小结果集到“海明威 - 老人与海”