I was asked this recently, and I couldn't figure out the best way. We are trying to replicate Google's search results where the search terms are bolded (using a b tag) in the results.
Input Terms Output
The search is cool {sea} The <b>sea</b>rch is cool
Originally, I thought this was pretty easy:
String results(String input, String[] terms)
{
for(String term : terms)
{
input = input.replace(term, "<b>" + term + "</b>");
}
return input;
}
However, this isn't correct. For example:
Input Terms Output
The search is cool {sea, search} The <b>search</b> is cool
I struggled to figure out the best way to approach this. Obviously we can no longer find and replace immediately. I played around with using a Map<Integer,String>
where the key is the index returned by input.indexOf(term)
and the value is the term, but this seemed potentially unnecessary. Any improvements?
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;
}