蛋:
String str = "Don't trouble trouble until trouble troubles you"
Map<String,String> replacementMap = new HashMap<String,String>(){{put("trouble","replaceStr");}};
我想要的输出是:
"Don't troubleStr troubleStr until troubleStr troubles you."
场景是我有一个段落,我也有一个关键字数据库,当我在网页上显示该段落时,我想突出显示匹配的关键字并替换链接目标。
最佳答案
String str = "Don't trouble trouble until trouble troubles you";
Map<String,String> replacementMap = new HashMap<String, String>(){{put("trouble","replaceStr");}};
for (Map.Entry<String, String> entry : replacementMap.entrySet()) {
System.out.println(entry.getKey()); //trouble
System.out.println(entry.getValue()); // replaceStr
str = str.replace(entry.getKey(), entry.getValue());
}
System.out.println(str);