Saq*_*med 5 java replace replaceall
昨天我正在制作定制的信件和备忘录.我制作了映射关键字,如:[Dateofbirth],[Email],[Employee],[Salary]等,它们将在生成时替换.
示例:亲爱的[员工],您的当前薪水是[薪水].
预期产量:
输出:亲爱的约翰,你目前的薪水是12000.
我在replaceAll()
这里使用的方法是一个代码.
String str = "dear [Employee], your Current Salary is [Salary].";
Map<String,String> vals = new HashMap<String,String>();
vals.put("[Employee]","John");
vals.put("[Salary]","12000");
for(String key:vals.keySet()){
str=str.replaceAll(key,vals.get(key));
}
System.out.println(str);
Run Code Online (Sandbox Code Playgroud)
但是出来的是:
dJohn1200012000 [JohnJohnJohnJohnJohnJohnJohnJohn], JohnJohnu12000 Cu1200012000Johnnt 1200012000John1200012000John is [1200012000John1200012000John].
Run Code Online (Sandbox Code Playgroud)
我很困惑,谷歌搜索它并试图使其正确,之后我改变replaceAll()
了replace()
EX: str=str.replace(key,vals.get(key));
Run Code Online (Sandbox Code Playgroud)
现在工作正常.问题是为什么替换所有正在做这种行为的核心概念是什么replaceAll()
,何时使用replace()
何时使用replaceAll()
.谢谢