转载

String.format()

1、String.format()使用

语法:
String.format(format,args...)

format:字符串格式。
args...:字符串格式中由格式说明符引用的参数。如果还有格式说明符以外的参数,则忽略这些额外的参数。参数的数目是可变的,可以为0。
1.1 转换符

转换符 说明 示例
%s 字符串类型 "mingrisoft"
%c 字符类型 'm'
%b 布尔类型 true
%d 整数类型(十进制) 99
%x 整数类型(十六进制) FF
%o 整数类型(八进制) 77
%f 浮点类型 99.99
%a 十六进制浮点类型 FF.35AE
%e 指数类型 9.38e+5
%g 通用浮点类型(f和e类型中较短的)
%h 散列码
%% 百分比类型
%n 换行符
%tx 日期与时间类型(x代表不同的日期与时间转换符 )

示例:

public static void main(String[] args) {
    String str=null;
    str=String.format("Hi,%s", "飞龙");          // 格式化字符串
    System.out.println(str);                             // 输出字符串变量str的内容
    System.out.printf("字母a的大写是:%c %n", 'A');
    System.out.printf("3>7的结果是:%b %n", 3>7);
    System.out.printf("100的一半是:%d %n", 100/2);
    System.out.printf("100的16进制数是:%x %n", 100);
    System.out.printf("100的8进制数是:%o %n", 100);
    System.out.printf("50元的书打8.5折扣是:%f 元%n", 50*0.85);
    System.out.printf("上面价格的16进制数是:%a %n", 50*0.85);
    System.out.printf("上面价格的指数表示:%e %n", 50*0.85);
    System.out.printf("上面价格的指数和浮点数结果的长度较短的是:%g %n", 50*0.85);
    System.out.printf("上面的折扣是%d%% %n", 85);
    System.out.printf("字母A的散列码是:%h %n", 'A');
}

1.2 搭配转换符的标志

标志 说明 示例 结果
+ 为正数或者负数添加符号 ("%+d",15) +15
左对齐 ("%-5d",15) 15
0 数字前面补0 ("%04d", 99) 0099
空格 在整数之前添加指定数量的空格 ("% 4d", 99) 99
, 以“,”对数字分组 ("%,f", 9999.99) 9,999.990000
( 使用括号包含负数 ("%(f", -99.99) (99.990000)
# 如果是浮点数则包含小数点,如果是16进制或8进制则添加0x或0 ("%#x", 99)、("%#o", 99) 0x63、0143
< 格式化前一个转换符所描述的参数 ("%f和%\<3.2f", 99.45) 99.450000和99.45
$ 被格式化的参数索引 ("%1$d,%2$s", 99,"abc") 99,abc

示例:

public static void main(String[] args) {
    String str=null;
    str=String.format("格式参数$的使用:%1$d,%2$s", 99,"abc");           // 格式化字符串
    System.out.println(str);                                                                                     // 输出字符串变量
    System.out.printf("显示正负数的符号:%+d与%d%n", 99,-99);
    System.out.printf("最牛的编号是:%03d%n", 7);
    System.out.printf("Tab键的效果是:% 8d%n", 7);
    System.out.printf("整数分组的效果是:%,d%n", 9989997);
    System.out.printf("一本书的价格是:%2.2f元%n", 49.8);
}

1.3 常见日期和时间组合的格式

转换符 说明 示例
c 包括全部日期和时间信息 星期六-十月-27-14:21:20-CST-2007
F “年-月-日”格式 2007-10-27
D “月/日/年”格式 10/27/07
r “HH:MM:SS - PM”格式(12时制) 02:25:51-下午
T “HH:MM:SS”格式(24时制) 14:28:16
R “HH:MM”格式(24时制) 14:28

示例:

public static void main(String[] args) {
    Date date=new Date();                                                                    // 创建日期对象
    System.out.printf("全部日期和时间信息:%tc%n",date);                // 格式化输出日期或时间
    System.out.printf("年-月-日格式:%tF%n",date);
    System.out.printf("月/日/年格式:%tD%n",date);
    System.out.printf("HH:MM:SS PM格式(12时制):%tr%n",date);
    System.out.printf("HH:MM:SS格式(24时制):%tT%n",date);
    System.out.printf("HH:MM格式(24时制):%tR",date);
}

1.4 日期格式化转换符

转换符 说明 示例
b或者h 月份简称 中:十月=英:Oct
B 月份全称 中:十月=英:October
a 星期的简称 中:星期六=英:Sat
A 星期的全称 中:星期六=英:Saturday
C 年的前两位数字(不足两位前面补0) 20
y 年的后两位数字(不足两位前面补0) 07
Y 4位数字的年份(不足4位前面补0) 2007
j 一年中的天数(即年的第几天) 300
m 两位数字的月份(不足两位前面补0) 10
d 两位数字的日(不足两位前面补0) 27
e 月份的日(前面不补0) 5

示例:

public static void main(String[] args) {
    Date date=new Date();                                                                             // 创建日期对象
    String str=String.format(Locale.US,"英文月份简称:%tb",date);      // 格式化日期字符串
    System.out.println(str);                                                                              // 输出字符串内容
    System.out.printf("本地月份简称:%tb%n",date);
    str=String.format(Locale.US,"英文月份全称:%tB",date);
    System.out.println(str);
    System.out.printf("本地月份全称:%tB%n",date);
    str=String.format(Locale.US,"英文星期的简称:%ta",date);
    System.out.println(str);
    System.out.printf("本地星期的简称:%tA%n",date);
    System.out.printf("年的前两位数字(不足两位前面补0):%tC%n",date);
    System.out.printf("年的后两位数字(不足两位前面补0):%ty%n",date);
    System.out.printf("一年中的天数(即年的第几天):%tj%n",date);
    System.out.printf("两位数字的月份(不足两位前面补0):%tm%n",date);
    System.out.printf("两位数字的日(不足两位前面补0):%td%n",date);
    System.out.printf("月份的日(前面不补0):%te",date);
}

1.5 时间格式化转换符

转换符 说明 示例
H 2位数字24时制的小时(不足2位前面补0) 15
I 2位数字12时制的小时(不足2位前面补0) 03
k 2位数字24时制的小时(前面不补0) 15
l 2位数字12时制的小时(前面不补0) 3
M 2位数字的分钟(不足2位前面补0) 03
S 2位数字的秒(不足2位前面补0) 09
L 3位数字的毫秒(不足3位前面补0) 015
N 9位数字的毫秒数(不足9位前面补0) 562000000
p 小写字母的上午或下午标记 中:下午=英:pm
z 相对于GMT的RFC822时区的偏移量 +0800
Z 时区缩写字符串 CST
s 1970-1-1=00:00:00=到现在所经过的秒数 1193468128
Q 1970-1-1=00:00:00=到现在所经过的毫秒数 1193468128984

示例:

public static void main(String[] args) {
    Date date=new Date();                               // 创建日期对象
    System.out.printf("2位数字24时制的小时(不足2位前面补0):%tH%n",date);
    System.out.printf("2位数字12时制的小时(不足2位前面补0):%tI%n",date);
    System.out.printf("2位数字24时制的小时(前面不补0):%tk%n",date);
    System.out.printf("2位数字12时制的小时(前面不补0):%tl%n",date);
    System.out.printf("2位数字的分钟(不足2位前面补0):%tM%n",date);
    System.out.printf("2位数字的秒(不足2位前面补0):%tS%n",date);
    System.out.printf("3位数字的毫秒(不足3位前面补0):%tL%n",date);
    System.out.printf("9位数字的毫秒数(不足9位前面补0):%tN%n",date);
    String str=String.format(Locale.US,"小写字母的上午或下午标记(英):%tp",date);
    System.out.println(str);                          // 输出字符串变量str的内容
    System.out.printf ("小写字母的上午或下午标记(中):%tp%n",date);
    System.out.printf("相对于GMT的RFC822时区的偏移量:%tz%n",date);
    System.out.printf("时区缩写字符串:%tZ%n",date);
    System.out.printf("1970-1-1 00:00:00 到现在所经过的秒数:%ts%n",date);
    System.out.printf("1970-1-1 00:00:00 到现在所经过的毫秒数:%tQ%n",date);
}

2、String.format()源码分析

    public static String format(String format, Object... args) {
        return new Formatter().format(format, args).toString();
    }

    public Formatter format(String format, Object ... args) {
        return format(l, format, args);
    }

    public Formatter format(Locale l, String format, Object ... args) {
        ensureOpen();

        // index of last argument referenced
        int last = -1;
        // last ordinary index
        int lasto = -1;

        FormatString[] fsa = parse(format);
        for (int i = 0; i < fsa.length; i++) {
            FormatString fs = fsa[i];
            int index = fs.index();
            try {
                switch (index) {
                case -2:  // fixed string, "%n", or "%%"
                    fs.print(null, l);
                    break;
                case -1:  // relative index
                    if (last < 0 || (args != null && last > args.length - 1))
                        throw new MissingFormatArgumentException(fs.toString());
                    fs.print((args == null ? null : args[last]), l);
                    break;
                case 0:  // ordinary index
                    lasto++;
                    last = lasto;
                    if (args != null && lasto > args.length - 1)
                        throw new MissingFormatArgumentException(fs.toString());
                    fs.print((args == null ? null : args[lasto]), l);
                    break;
                default:  // explicit index
                    last = index - 1;
                    if (args != null && last > args.length - 1)
                        throw new MissingFormatArgumentException(fs.toString());
                    fs.print((args == null ? null : args[last]), l);
                    break;
                }
            } catch (IOException x) {
                lastException = x;
            }
        }
        return this;
    }


http://qiniu.openmuch.com/1576653445%281%29.jpg

    private class FixedString implements FormatString {
        private String s;
        FixedString(String s) { this.s = s; }
        public int index() { return -2; }
        public void print(Object arg, Locale l)
            throws IOException { a.append(s); }
        public String toString() { return s; }
    }

看到其中的 a.append(s);实现如下

    private static final Appendable nonNullAppendable(Appendable a) {
        if (a == null)
            return new StringBuilder();

        return a;
    }
正文到此结束