Java基础扫盲系列(-)—— String中的format

本文介绍了Java中的String.format()方法,该方法类似于C语言中的printf,用于格式化字符串输出。文章详细解释了Formatter的语法结构及其在Java中的应用示例。

Java基础扫盲系列(-)—— String中的format

以前大学学习C语言时,有函数printf,能够按照格式打印输出的内容。但是工作后使用Java,也没有遇到过格式打印的需求,今天遇到项目代码使用String.format()工具api。

这里完善知识体系,将Java中的formatter简单的总结下。

An interpreter for printf-style format strings. This class provides support for layout justification and alignment, common formats for numeric, string, and date/time data, and locale-specific output. Common Java types such as {@code byte}, {@link java.math.BigDecimal BigDecimal}, and {@link Calendar} are supported. Limited formatting customization for arbitrary user types is provided through the {@link Formattable} interface.

Java docs中是这样描述Formatter的:

格式化打印字符串的拦截器。Formatter提供对布局和对齐,格式化数值、字符串、日期时间和特定的本地化输出的能力。甚至连常用的BigDecimal,Calendar,byte类型都提供了支持。

先来看下简单的例子,认识下Formatter的格式能力:

int a = 1;
int b = 100;

System.out.println(String.format("%03d", a));
System.out.println(String.format("%03d", b));

输出结果:

001
100

大致可以看出formatter的能力了吧。将参数按照设定的格式进行格式化。

Formatter是Java SE 5提供的api,就是为了对格式化提供支撑。常用的字符和数值类型的格式化语法如下:

%[argument_index$][flags][width][.precision]conversion

  • argument_index$可选参数,用来按照位置指定参数,1$表示第一个参数;
  • flags是可选参数,是一个字符集用来控制输出格式,依赖后面的转换conversion;
  • width可选参数,是一个非负的整型,用来控制输出的字符个数;
  • precision可选参数,是一个非负整型,用来控制小数点后的个数;
  • conversion必选,是一个字符,用来表示参数怎样被格式化;

对于各个参数想详细信息和日期时间,甚至其功能的格式化(大小写转换),请参考api文档: Class Formatter

在Java字节的类库中也有大量使用Formatter的痕迹:

  • String类提供的静态api

      public static String format(String format, Object... args) {
          return new Formatter().format(format, args).toString();
      }
  • System.out.printf():

      public PrintStream printf(String format, Object ... args) {
          return format(format, args);
      }
    
       public PrintStream format(String format, Object ... args) {
          try {
          synchronized (this) {
              ensureOpen();
              if ((formatter == null)
                  || (formatter.locale() != Locale.getDefault()))
                  formatter = new Formatter((Appendable) this);
              formatter.format(Locale.getDefault(), format, args);
          }
          } catch (InterruptedIOException x) {
          Thread.currentThread().interrupt();
          } catch (IOException x) {
          trouble = true;
          }
          return this;
      }

这些地方都是对Formatter的格式化能力包装后提供的简洁api。

转载于:https://www.cnblogs.com/lxyit/p/9366591.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值