业务中有时候要输出一些文案模板
方法一
自己通过字符串替换函数实现
String str = "我叫{name},我来自{city},今年{age}岁";
Map mapstring = new HashMap<>();
mapstring.put("name", "小明");
mapstring.put("age", "20");
mapstring.put("city", "上海");
for (Map.Entry entry : mapstring.entrySet()) {
str = str.replace("{" + entry.getKey() + "}", entry.getValue());
}
System.out.println(str);
结果为
我叫小明,我来自上海,今年20岁
方法二
通过hutool 工具实现
Map mapstring = new HashMap<>();
mapstring.put("name", "小明");
mapstring.put("age", "20");
mapstring.put("city", "上海");
System.out.println(StrUtil.format(str, mapstring));
输出
我叫小明,我来自上海,今年20岁
作者:良人与我