**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);
你这个效率不高,100个变量就会遍历100次string,并且有100个中间对象生成
Sign in to make a reply
庭除闲步
**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);