String.format(String format, Object… args)

版权声明:+1s https://blog.csdn.net/qq997404392/article/details/78326822

定义

public static String format(String format, Object… args);
使用本地语言环境、指定的格式字符串和参数返回一个格式化字符串。

参数:
format - 格式字符串
args - 格式字符串中由格式说明符引用的参数。如果还有格式说明符以外的参数,则忽略这些额外的参数。参数的数目是可变的,可以为 0。参数的最大数目受 Java Virtual Machine Specification 所定义的 Java 数组最大维度的限制。有关 null 参数的行为依赖于转换。

返回:
一个格式化字符串

抛出:
IllegalFormatException - 如果格式字符串中包含非法语法、与给定的参数不兼容的格式说明符,格式字符串给定的参数不够,或者存在其他非法条件。
NullPointerException - 如果 format 为 null

从以下版本开始:
1.5

格式化语法

产生格式化输出的每个方法都需要格式字符串和参数列表。格式字符串是一个 String,它可以包含固定文本以及一个或多个嵌入的格式说明符。

常规类型、字符类型和数值类型的格式说明符的语法

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

可选 argument_index 是一个十进制整数,用于表明参数在参数列表中的位置。第一个参数由 “1$” 引用,第二个参数由 “2$” 引用,依此类推。

可选 flags 是修改输出格式的字符集。有效标志集取决于转换类型。

可选 width 是一个非负十进制整数,表明要向输出中写入的最少字符数。

可选 precision 是一个非负十进制整数,通常用来限制字符数。特定行为取决于转换类型。

所需 conversion 是一个表明应该如何格式化参数的字符。给定参数的有效转换集取决于参数的数据类型。

转换符说明

这里写图片描述

Eg1:说明argument_index和width

System.out.println(msg);
String s =  String.format("this is a %2$s %1$s %s %s test", "java", "C++");

this is a C++ java java C++ test

Eg2.说明 flags

System.out.println(String.format("%1$,09d", -3872));
System.out.println(String.format("%1$,010d", -3872));
System.out.println(String.format("%1$,09d", 3872));
System.out.println(String.format("%1$9d", -14));
System.out.println(String.format("%1$-9d", -14));
System.out.println(String.format("%1$(9d", -14));
System.out.println(String.format("%1$#9x", 31));

-0003,872
-00003,872
00003,872
      -14
-14     
     (14)
     0x1f

Eg3:说明conversion

System.out.println(String.format("this is:%s %s", "string", "format"));
System.out.println(String.format("%b, %b, %b, %b, %b, %b", "true",true, false, null, 0>1, 1, ""));
System.out.println(String.format("%o", 31));
System.out.println(String.format("%x", 31));
System.out.println(String.format("%e", 12345.6987));
System.out.println(String.format("%a", 12345.6987));
System.out.println(String.format("%c, %c, %c, %c", 'a', 'b', 48, 98));

this is:string format
true, true, false, false, false, true
37
1f
1.234570e+04
0x1.81cd96f0068dcp13
a, b, 0, b

另外,这篇文章有更详细的进阶说明:
http://www.cnblogs.com/travellife/p/Java-zi-fu-chuan-ge-shi-hua-xiang-jie.html

猜你喜欢

转载自blog.csdn.net/qq997404392/article/details/78326822