java stringformatter_Java 字符串格式化 —— java.util.Formatter

标签:

java.util.Formatter是JDK1.5新增的类,支持类似C中的printf风格的字符串格式化工作

Formatter有4个构造方法,如下:

public Formatter()

public Formatter(Appendable a)

public Formatter(Locale l)

public Formatter(Appendable a, Locale l)

构造方法主要用于设置Formatter的缓冲器和Locale,默认的情况下,Formatter使用StringBuilder作为缓冲器,使用Locale.getDefault()作为locale。

Formatter的使用方法如下(摘自JDK DOC):StringBuilder sb = new StringBuilder();

// Send all output to the Appendable object sb

Formatter formatter = new Formatter(sb, Locale.US);

// Explicit argument indices may be used to re-order output.

formatter.format("%4$2s %3$2s %2$2s %1$2s", "a", "b", "c", "d")

// -> " d  c  b  a"

// Optional locale as the first argument can be used to get

// locale-specific formatting of numbers.  The precision and width can be

// given to round and align the value.

formatter.format(Locale.FRANCE, "e = %+10.4f", Math.E);

// -> "e =    +2,7183"

// The ‘(‘ numeric flag may be used to format negative numbers with

// parentheses rather than a minus sign.  Group separators are

// automatically inserted.

formatter.format("Amount gained or lost since last statement: $ %(,.2f", balanceDelta);

// -> "Amount gained or lost since last statement: $ (6,217.58)"

例子中,先new一个Formatter对象,然后调用Formatter的format方法,这时Formatter内部的缓冲器就储存了格式化后的字符串,然后可以用toString方法取出。

更为一般的用法是使用String.format,String.format通过Formatter实现字条串格式public static String format(String format, Object ... args) {

return new Formatter().format(format, args).toString();

}

或者在输出流中使用System.out.format("Local time: %tT", Calendar.getInstance());

format方法的主要参数分两部分,格式字符串和可变的格式化参数

格式字符串有一套自己的语法,它由固定文本或者格式描述符组成。描述符的格式如下:%[argument_index$][flags][width][.precision]conversion

argument_index是一个整数,表明使用的参数的位置,例如System.out.format("%d %d", 1, 2);        // 输出 1 2

System.out.format("%1$d %d", 1, 2);      // 输出 1 1

flags是一组用于修饰输出的字条

width是一个非负的整数,用于指定写到绥中的最小长度

precision是一个非负整数,一般用于指定数字的精度,依赖conversion

conversion必须有值,用于指定参数如何转换

conversion主要有以下几组字符(即可以转换的类型)

‘s‘,‘S‘             要求参数实现了Formattable,然后调用它的formatTo方法得到结果

‘c‘,‘C‘        字符

‘d‘             十进制整数

‘o‘             八进制整数

‘x‘,‘X‘        十六进制整数

‘e‘,‘E‘        科学计数法浮点数

‘f‘             浮点数

‘t‘,‘T‘        时间日期

flags主要有以下几种用法

‘-‘                            左对齐

‘#‘                            依赖于conversion,不同的conversion,该flag的含义不一样

‘+‘                            结果带正负号

‘ ‘                             结果带前置空格

‘0‘                            如果结果不满足宽度(width参数)的要求,用0字符填充

‘,‘                            数字会按locale用逗号分割

‘(‘                            负数结果会被括号括起

更详细的资料可以看JDK文档

标签:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值