该函数用于用相应的值替换字符串中的某些子字符串。替换字符串中的多个子字符串
//地图(string_to_replace,string_to_replace_with)
String template = "ola ala kala pala sala";
StringBuilder populatedTemplate = new StringBuilder();
HashMap<String, String> map = new HashMap<>();
map.put("ola", "patola");
map.put("pala", "papala");
int i=0;
for (String word : template.split("'")) {
populatedTemplate.append(map.getOrDefault(word, word));
populatedTemplate.append(" ");
}
System.out.println(populatedTemplate.toString());
此上述功能工作正常,如果要被替换字符串为““(空格)所包围。
Ex- String =>“嘿{how} are $ = you” 如果要替换的子字符串是“嗨”或“你”,那么它工作正常。问题是我想要替换“如何”和“你”。
如何在不增加复杂度的情况下实现这一目标?
为什么不'template.replace(string_to_replace,string_to_replace_with)'往往你需要? PS:http://stackoverflow.com/questions/1324676/what-is-a-word-boundary-in-regexes可能工作,否则。 – zapl
@zapl这个问题与替换是相关的。即让我想将“如何”替换为“是”,将“是”替换为“OK”。在第一次迭代之后,字符串将是“嘿,你是$你”。并在第二次迭代“嘿{ok}确定$ =你”之后。指出错误的输出。它应该是“嗨,你好”$ =你“ – tarun14110