在程序实现中,我们经常会在一些字符串内部需要插入一些变量。
当然直接用String,StringBuffer,StringBuilder拼接是完全没有问题的。
这里讲另外两种方式:
1、使用
MessageFormat.format(String pattern, Object.. arg);
例如:
<h3>{0}申请进度</h3>
<div>申请人:<span style="font-weight:bold">{1}</span></div>
<div>您的申请【单号:{2,number,#}】审批通过。</div>
<div>审批人:<span style="font-weight:bold">{3}。</span></div>
<div>下级审批人:<span style="font-weight:bold">{4}</span></div>
上面的{2,number,#}
,是格式化数字型的参数。默认有千分位,【10,000】。保留小数可写成:##.##
还支持其他类型的参数,例如日期型等。
2、使用
String.format(String format, Object... args);
例如:
String.format("Hello %s, %s, %s", "hanmeimei", "liming", "lucy");
console:
Hello hanmeimei, liming, lucy