【发布时间】:2014-03-28 16:47:30
【问题描述】:
最近有人问我这个问题,但我想不出最好的方法。我们正在尝试复制 Google 的搜索结果,其中搜索词在结果中以粗体显示(使用 b 标签)。
Input Terms Output
The search is cool {sea} The <b>sea</b>rch is cool
最初,我认为这很容易:
String results(String input, String[] terms)
{
for(String term : terms)
{
input = input.replace(term, "<b>" + term + "</b>");
}
return input;
}
但是,这是不正确的。例如:
Input Terms Output
The search is cool {sea, search} The <b>search</b> is cool
我努力想办法解决这个问题。显然我们不能再立即找到并替换。我尝试使用Map<Integer,String>,其中键是术语,值是input.indexOf(term) 返回的索引,但这似乎可能没有必要。有什么改进吗?
public String results(String input, String[] terms)
{
Map<Integer, String> map = new HashMap<Integer,String>();
for(String term : terms)
{
int index = input.indexOf(term);
if(index >= 0)//if found
{
String value = map.get(index);
if(value == null || value.length() < term.length())//use the longer term
map.put(index, term);
}
}
for(String term: map.values())
{
input = input.replace(term, "<b>" + term + "</b>");
}
return input;
}
【问题讨论】:
-
如果它已经在工作,你应该把它发布到codereview.stackexchange.com。
-
先将术语从最短到最长排序并删除重复项,然后执行此操作!