Java字符串格式

时间:2020-02-23 14:36:55  来源:igfitidea点击:

Java String格式允许我们以特定的方式或者顺序放置事物。
字符串格式化的方法有很多,但并不是很流行,因为大多数时候我们需要可以通过字符串连接完成的简单转换。
今天,我们将研究java字符串格式的示例。

Java字符串格式

Java以C开头的格式化字符串概念,Java还提供了使用称为java.util.Formatter的类进行格式化打印的功能。
实际上,Java的格式化String概念是受C的sprintf概念启发的。

让我们看一下简单的String格式方法的外观。

String formattedString = String.format("My name is %s","John");

上面的一个班轮代码将输出为:

My name is John

可以通过"我的名字是" +"约翰"来实现相同的目的,在这里我们甚至不必记住所有不同的说明符。
但是,由于以下原因,字符串格式化程序是一种更好的方法:

  • 字符串连接是一项昂贵的事务。

  • 如果格式化的字符串很长,则字符串连接会导致可读性问题。

  • 使用字符串连接,我们必须在不同对象之间转换为字符串。

  • 从属性文件中读取格式字符串时,可以清楚地看到String Formatter的好处。

String.format()方法根据String格式和提供给该方法的参数返回格式化的String。

在上面的示例中,"我的名字是%s"是格式字符串。
它包含一个格式说明符"%s",它指示应如何处理参数以及将其放置在输出中的位置。

format方法还使用语言环境来格式化字符串。
如果在String.format()方法中未指定语言环境,则通过调用Locale.getDefault()方法使用默认语言环境。

Java字符串格式示例

在某些情况下,我们希望格式化的字符串出现在控制台上。
从调试到更易读的代码,其用法可能有所不同。
为了在控制台上获取格式化的字符串,我们需要使用以下方法。

  • System.out.printf()
  • System.err.printf()

printf()和format()方法的行为相同。
下面提供了上述方法的示例。

  • System.out.printf():最常用于在控制台上打印以进行调试或者在屏幕上打印输出。
int num1 = 2;
int num2 = 3;
int  result = num1 * num2;

System.out.printf("The result of %d * %d = %d", num1,num2,result);

输出:

The result of 2 * 3 = 6
  • System.err.printf():通常用于在控制台上打印错误。
    还可以在控制台上提供自定义错误消息。
try {
		int num1 = 2;
		int num2 = 0;
		int  result = num1/num2;
		System.out.printf("The result of %d/%d = %d", num1,num2,result);
	} catch(Exception ex) {
		System.err.printf("Error occurred with cause: %s", ex.getMessage());		
	}

输出:

Error occurred with cause:/by zero

Java String Fromatter与StringBuffer和StringBuilder

我们也可以将格式化程序与StringBuffer和StringBuilder一起使用。

StringBuilder sb = new StringBuilder();
Formatter formatter = new Formatter(sb);
Formatter.format("value is %f",32.33434); 
System.out.print(sb.toString());

输出:

value is 32.334340

Java字符串格式转换说明符

Java字符串格式转换说明符是在字符串格式化中起主要作用的说明符。
作为说明符的是那些说明如何处理转换以及在文本中在何处添加自变量的说明符。

让我们看一下可用的转换说明符及其示例。

Conversion SpecifierAppliesToDescriptionExample CodeOutput
%a,%AFloating pointThe result is a hexadecimal representation of the floating point numberString.format("Hex is %a";,32.33434);Hex is 0x1.02acba732df5p5
%b, %BAll the typesIf the argument arg is null, then the result is "false";. If arg is a boolean or Boolean, then the result is the string returned by String.valueOf(arg). Otherwise, the result is "true";.String.format("value is %b";,";a";.equals("a";));value is true
%c, %CCharacterResults in a Unicode characterString.format("Unicode is %C";,'T');Unicode is T
%dbyte, Byte, short, Short, int, Integer, long, Long and BigIntegerResults in decimal integerString.format("Number is %d";, 2*3);Number is 6
%e, %EFloating pointResults in decimal number in computerized scientific notationString.format("Number is %e";, 2*3.0);Number is 6.000000e+00
%fFloating pointResults in decimal numberString.format("Number is %f";, 2*3.0);Number is 6.000000
%g, %GFloating pointFormat is based on computerized scientific notation or decimal format, depending on the precision and the value after rounding.String.format("Number is %g";, 2*3.0);Number is 6.000000
%h, %HAny typeResults in hex string based on the output of hashCode() methodString.format("Hex is %h";,";Jay";);Hex is 12202
%nLine separatorResults in platform specific line separatorString.format("My name is %s. %n I know Java ",";John";);My name is John.I know Java
%obyte, Byte, short, Short, int, Integer, long, Long and BigIntegerResults in an octal integerString.format("Number is %o";, 3*3);Number is 11
%sAny typeResults in a stringString.format("My name is %s";,";John";);My name is John
%t, %TDate and TimeThese are prefix for date and time conversion charactersString.format("Local time: %tT";, Calendar.getInstance());Local time: 17:52:40
%x, %Xbyte, Byte, short, Short, int, Integer, long, Long and BigIntegerResults in a hexadecimal integerString sf1=String.format("Number is %x";, 23);Number is 17

以大写字母表示的转换(即'B','H','S','C','X','E','G','A'和'T')与对应于小写转换字符的字符,唯一的区别是根据语言环境的规则将结果转换为大写。

Java字符串格式的日期和时间转换

以下日期和时间转换字符与后缀" t"和" T"一起用作后缀,用于日期和时间转换。

示例:%tA将产生星期几的全名。

Conversion SpecifierDescription
AFull name of the day of the week, like "Sunday";, "Monday";
aShort name of the day of the week, like "Mon";, "Tue";
BFull month name like "January";, "February";.
bShort name of the month like "Jan";, "Feb";.
CLast two digits of the year, starting from 00 to 99
cDate and time formatted as "%ta %tb %td %tT %tZ %tY";, like "Mon Jan 01 16:17:00 CST 2016";
DDate formatted as "%tm/%td/%ty";, like "12/31/17";
dDay represented in two digits with leading zeros where necessary, starting from 01 to 31.
eDay of month represented in two digits, like 1 – 31.
FDate formatted in ISO 8601 format as "%tY-%tm-%td"; like "2016-12-31";
HHour representation in 24 hours format with a leading zero as necessary i.e. 00 – 23.
hShort name of the month like "Jan";, "Feb";.
IHour represented in 12 hour format, formatted as two digits with a leading zero as necessary, i.e. 01 – 12.
jDay of the year out of 366 days (considering leap year), represented with leading 0s i.e. "001"; to "366";.
kHour representation in 24 hour format without a leading 0 starting from "0"; to "23";.
lHour representation in 12-hour format without a leading 0 like "1"; to "12";.
LMillisecond within the second formatted represented in three digits with leading zeros starting from 000 to 999.
MMinute within the hour formatted leading zero starting from "00"; to "59";.
mMonth formatted with a leading zero like "01"; to "12";.
NNanosecond with in the second represented in 9 digits and leading 0s like "000000000"; to "999999999";.
pLocale specific morning or afternoon specifier like "am"; or "pm"; marker.
QMilliseconds since the start of epoch Jan 1 , 1970 00:00:00 UTC.
RTime represented in 24-hours format i.e. "%tH:%tM"; like "20:00";
rTime represented,in 12-hours format i.e "%tI:%tM:%tS %Tp";.
SSeconds within the minute represented in 2 digits like "00"; to "60";. "60"; is required to support leap seconds.
sSeconds since the start of epoch Jan 1, 1970 00:00:00 UTC.
TTime represented in 24 hours format along with seconds as "%tH:%tM:%tS";
YYear represented in four digits starting from,";0000" to "9999";
yYear represented in two digits starting from "00"; to "99";
ZTime zone representation in string like "IST";, "CST"; etc.
zNumeric time zone offset based on RFC 822 like "-0530";

Java字符串格式宽度

输出所需的最少字符数被视为宽度。
因为宽度不适用或者宽度不正确,所以会引发换行符转换异常。

//Width for Integer
String s = String.format("{%10d}", 2016);
System.out.print(s);

//Width for String
String s1 = String.format("{%20s}", "Hello Format");
System.out.print(s1);

输出:

{      2016}
{        Hello Format}

Java字符串格式精度

精度是整数和字符串要写入输出的最大字符数。

浮点转换" a"," A"," e"," E"和" f"的精度为小数点后的位数。
如果转换是" g"或者" G",则精度是四舍五入后得到的幅度中的位数总数。

字符,整数和日期/时间参数类型以及百分比和行分隔符转换都会引发异常,因为精度不适用于这些类型。

String s = String.format("{%.8s}", "Hello Format");

System.out.print(s);

输出:

{Hello Fo}

Java字符串格式参数索引

参数索引是十进制整数,以"%"号开头,以" $"号结尾。
参数在参数列表中的位置取决于整数值。

String s = String.format("{%3$s %2$s %1$s}", "a","b","c");
System.out.print(s);

输出:

{c b a}

其他字符串格式化示例

到目前为止,我们已经观察到各种转换说明符及其用法。
在最后一部分中,让我们检查一些其他的杂项转换。

  • 文本的左对齐。
String s = String.format ("{%4s}", "a");
System.out.print(s);

输出:

{   a}
  • 文本的右对齐。
String s = String.format ("{%-4s}", "a");
System.out.print(s);

输出:

{a   }
  • 特定于语言环境的数字格式表示形式。
String s = String.format ("{%,d}", 1000000);
System.out.print(s);

输出:

{1,000,000}
  • 填充为零。
String s = String.format ("{%05d}", 99);
System.out.print(s);

输出:

{00099}