java字符串格式化处理技巧

男娘i 2022-09-23 13:47 103阅读 0赞

java字符串格式化处理技巧

介绍

  1. 有时我们可能想要获得指定格式的字符串信息,有些数据是根据动态获取的,
  2. 那么使用String的静态方法format(String string,Object...args)是一个不错的选择。

应用场景

  1. 本人开发中接触到的是短信模板动态填充内容,这算一个小知识点。

String format静态方法

format静态方法

  1. //Returns a formatted string using the specified format string and arguments.
  2. public static String format(String format, Object... args) {
  3. return new Formatter().format(format, args).toString();
  4. }
  5. public static String format(Locale l, String format, Object... args) {
  6. return new Formatter(l).format(format, args).toString();
  7. }

格式化参数和使用

  1. 常用转换符 说明
  2. %s 字符串类型
  3. %c 字符类型
  4. %b 布尔类型
  5. %d 整数类型(十进制)
  6. %f 浮点类型
  7. %% 百分比类型
  8. ...
  9. 其实还有很多比如日期格式化参数,但是我并不推荐掌握那么多,开发中大多数情况下%s都能满足的。
  10. 最后实在无法达到需求,那么自己转换下或再查文档不迟。

使用Code

  1. System.out.println(String.format("hello %s", "world"));//hello world
  2. System.out.println(String.format("hello %c", 'a'));//hello a
  3. System.out.println(String.format("hello %b", false));//hello false
  4. System.out.println(String.format("hello %d", 15));//hello 15
  5. System.out.println(String.format("hello %f", 3.14));//hello 3.140000(注意帮我们算精度了,还是我们自己处理成String类型用%s传更好)
  6. System.out.println(String.format("合格率 %d%%", 20));//合格率 20%

总结

  1. jdk1.5之后,String类中增加两个format静态方法帮助我们格式化字符串数据,这也是一个小知识点我们应该掌握。

参考

1、http://blog.csdn.net/lonely_fireworks/article/details/7962171

发表评论

表情:
评论列表 (有 0 条评论,103人围观)

还没有评论,来说两句吧...

相关阅读