Discuss / Java / 我可以直接用 String.replaceAll() 实现

我可以直接用 String.replaceAll() 实现

Topic source

庭除闲步

#1 Created at ... [Delete] [Delete and Lock User]

**String s = "Hello, ${name}! You are learning ${lang}!";
**

Map<String, String> map = new HashMap<>();
map.put("name", "Bob");
map.put("lang", "Java");
for (String key : map.keySet()) {
     s = s.replaceAll("\\$\\{" + key + "}", map.get(key));
}
System.out.println(s);

廖雪峰

#2 Created at ... [Delete] [Delete and Lock User]

你这个效率不高,100个变量就会遍历100次string,并且有100个中间对象生成


  • 1

Reply