Yesterday I worked on personalized letters and notes. And I made cartographic keywords, such as: [Date of birth], [Email], [Employee], [Salary], etc., which will be replaced during the generation.
Example: dear [Employee], your current salary is [Salary].
expected output:
Conclusion: dear John, your current salary is 12,000.
I am using replaceAll() method, here is the code.
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);
but output:
dJohn1200012000 [JohnJohnJohnJohnJohnJohnJohnJohn], JohnJohnu12000 Cu1200012000Johnnt 1200012000John1200012000John is [1200012000John1200012000John].
I was confused and looked for it and tried to make it correct, after which I changed replaceAll() to replace()
EX: str=str.replace(key,vals.get(key));
Now it works fine. The question is why replacing everyone does this, which is the basic concept of replaceAll() and when to use replace() , when to use replaceAll() . Thanks