java字符串格式化处理技巧
java字符串格式化处理技巧
介绍
有时我们可能想要获得指定格式的字符串信息,有些数据是根据动态获取的,
那么使用String的静态方法format(String string,Object...args)是一个不错的选择。
应用场景
本人开发中接触到的是短信模板动态填充内容,这算一个小知识点。
String format静态方法
format静态方法
//Returns a formatted string using the specified format string and arguments.
public static String format(String format, Object... args) {
return new Formatter().format(format, args).toString();
}
public static String format(Locale l, String format, Object... args) {
return new Formatter(l).format(format, args).toString();
}
格式化参数和使用
常用转换符 说明
%s 字符串类型
%c 字符类型
%b 布尔类型
%d 整数类型(十进制)
%f 浮点类型
%% 百分比类型
...
其实还有很多比如日期格式化参数,但是我并不推荐掌握那么多,开发中大多数情况下%s都能满足的。
最后实在无法达到需求,那么自己转换下或再查文档不迟。
使用Code
System.out.println(String.format("hello %s", "world"));//hello world
System.out.println(String.format("hello %c", 'a'));//hello a
System.out.println(String.format("hello %b", false));//hello false
System.out.println(String.format("hello %d", 15));//hello 15
System.out.println(String.format("hello %f", 3.14));//hello 3.140000(注意帮我们算精度了,还是我们自己处理成String类型用%s传更好)
System.out.println(String.format("合格率 %d%%", 20));//合格率 20%
总结
jdk1.5之后,String类中增加两个format静态方法帮助我们格式化字符串数据,这也是一个小知识点我们应该掌握。
参考
1、http://blog.csdn.net/lonely_fireworks/article/details/7962171
还没有评论,来说两句吧...