天天看点

Java字符串格式

Java String format allows us to put things in particular way or order. There are many ways for string formatting but it’s not so popular because most of the time we need simple conversions that can be done with string concatenation. Today we will look into java string format examples.

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

Java字符串格式 (Java String Format)

The formatted String concept started with C, Java also provides the feature of formatted printing using the class known as

java.util.Formatter

. In fact, formatted String concept of Java is inspired by C’s

sprintf

concept.

Java以C开头的格式化字符串概念,Java还提供了使用称为

java.util.Formatter

的类进行格式化打印的功能。 实际上,Java的格式化String概念是受C的

sprintf

概念启发的。

Let us look at how a simple String format method looks like.

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

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

Above one liner code will output as:

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

My name is John
           

The same thing can be achieved as

"My name is "+"John"

and here we don’t even have to remember all the different specifiers. However String formatter is a better approach because of following reasons:

可以实现相同的事情,因为

"My name is "+"John"

,在这里我们甚至不必记住所有不同的说明符。 但是,由于以下原因,字符串格式化程序是一种更好的方法:

  • String concatenation is a costly affair.

    字符串串联是一项昂贵的事务。

  • If formatted string is long then string concatenation cause readability issues.

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

  • With String concatenation we have to do the conversion between different objects to strings.

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

  • String Formatter benefit is clearly visible where the format string is read from a property file.

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

The

String.format()

method returns the formatted String based on the format String and the arguments provided to the method.

String.format()

方法基于String格式和提供给该方法的参数返回格式化的String。

In the example above, “My name is %s” is the format string. It contains a format specifier “%s” which tells how the argument should be processed and where it will be placed in the output.

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

The format method also uses locale for formatting a string. If the locale is not specified in

String.format()

method, it uses default locale by calling 

Locale.getDefault()

 method.

format方法还使用语言环境来格式化字符串。 如果在

String.format()

方法中未指定语言环境,则通过调用

Locale.getDefault()

方法来使用默认语言环境。

Java字符串格式示例 (Java String Format Example)

There are situation and scenarios when we would like to have formatted string appear on the console; the usage of it can vary from debugging to better readable code. In order to get formatted strings on console we need to use the following methods.

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

  1. System.out.printf()

    System.out.printf()

  2. System.err.printf()

    System.err.printf()

printf()

and

format()

methods behave in the same way. The examples for the above mentioned methods are provided below.

printf()

format()

方法的行为相同。 下面提供了上述方法的示例。

  1. System.out.printf()

    : Most commonly used for printing on console for debugging purpose or for printing an output on the screen.

    System.out.printf()

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

    Output:

    输出:

    The result of 2 * 3 = 6
               
  3. System.err.printf(): Mostly used to print an error on console. Also to provide a custom error messages on console.

    System.err.printf():通常用于在控制台上打印错误。 还可以在控制台上提供自定义错误消息。

  4. 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());		
    	}
               

    Output:

    输出:

    Error occurred with cause: / by zero
               

Java String Fromatter与StringBuffer和StringBuilder (Java String Fromatter with StringBuffer and StringBuilder)

We can use formatter with StringBuffer and StringBuilder as well.

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

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

Output:

输出:

value is 32.334340
           

Java字符串格式转换说明符 (Java String Format Conversion Specifiers)

Java String Format conversion specifiers are the ones which plays a major role in String formatting. As the specifiers are the ones that tells how the conversion has to be processed and where to add the arguments in the text.

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

Lets take a look at the available conversion specifiers along with their examples.

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

Conversion Specifier

Applies

To

Description Example Code Output
%a,%A Floating point The result is a hexadecimal representation of the floating point number String.format(“Hex is %a”,32.33434); Hex is 0x1.02acba732df5p5
%b, %B All the types If 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, %C Character Results in a Unicode character String.format(“Unicode is %C”,’T’); Unicode is T
%d byte, Byte, short, Short, int, Integer, long, Long and BigInteger Results in decimal integer String.format(“Number is %d”, 2*3); Number is 6
%e, %E Floating point Results in decimal number in computerized scientific notation String.format(“Number is %e”, 2*3.0); Number is 6.000000e+00
%f Floating point Results in decimal number String.format(“Number is %f”, 2*3.0); Number is 6.000000
%g, %G Floating point Format 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, %H Any type Results in hex string based on the output of hashCode() method String.format(“Hex is %h”,”Jay”); Hex is 12202
%n Line separator Results in platform specific line separator String.format(“My name is %s. %n I know Java “,”John”);

My name is John.

I know Java

%o byte, Byte, short, Short, int, Integer, long, Long and BigInteger Results in an octal integer String.format(“Number is %o”, 3*3); Number is 11
%s Any type Results in a string String.format(“My name is %s”,”John”); My name is John
%t, %T Date and Time These are prefix for date and time conversion characters String.format(“Local time: %tT”, Calendar.getInstance()); Local time: 17:52:40
%x, %X byte, Byte, short, Short, int, Integer, long, Long and BigInteger Results in a hexadecimal integer String sf1=String.format(“Number is %x”, 23); Number is 17
转换说明符

适用

描述 范例程式码 输出量
%a,%A 浮点 结果是浮点数的十六进制表示形式 String.format(“十六进制为%a”,32.33434); 十六进制为0x1.02acba732df5p5
%b,%B 所有类型 如果参数arg为null,则结果为“ false”。 如果arg是布尔值或布尔值,则结果是String.valueOf(arg)返回的字符串。 否则,结果为“ true”。 String.format(“值是%b”,“ a” .equals(“ a”)); 值是真的
%c,%C 字符 结果为Unicode字符 String.format(“ Unicode为%C”,'T'); Unicode是T
%d byte,Byte,short,Short,int,Integer,long,Long和BigInteger 结果以十进制整数表示 String.format(“数字为%d”,2 * 3); 数是6
%e,%E 浮点 以计算机科学计数法得出十进制数的结果 String.format(“ Number is%e”,2 * 3.0); 数字为6.000000e + 00
%F 浮点 结果以十进制数表示 String.format(“数字为%f”,2 * 3.0); 数是6.000000
%g,%G 浮点 格式基于计算机科学计数法或十进制格式,具体取决于精度和四舍五入后的值。 String.format(“数字为%g”,2 * 3.0); 数是6.000000
%h,%H 任何类型 基于hashCode()方法输出的十六进制字符串结果 String.format(“十六进制为%h”,“ Jay”); 十六进制为12202
%n 行分隔符 产生平台特定的行分隔符 String.format(“我的名字是%s。%n我知道Java“,” John“);

我的名字是约翰。

我知道Java

%o byte,Byte,short,Short,int,Integer,long,Long和BigInteger 产生八进制整数 String.format(“数字为%o”,3 * 3); 数是11
%s 任何类型 结果为字符串 String.format(“我的名字是%s”,“ John”); 我的名字是约翰
%t,%T 日期和时间 这些是日期和时间转换字符的前缀 String.format(“本地时间:%tT”,Calendar.getInstance()); 当地时间:17:52:40
%x,%X byte,Byte,short,Short,int,Integer,long,Long和BigInteger 结果为十六进制整数 字符串sf1 = String.format(“ Number is%x”,23); 数是17

Conversions denoted by upper-case character (i.e. ‘B’, ‘H’, ‘S’, ‘C’, ‘X’, ‘E’, ‘G’, ‘A’, and ‘T’) are the same as those for the corresponding lower-case conversion characters only difference is that the result is converted to upper case according to the rules of the locale.

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

Java字符串格式的日期和时间转换 (Java String Formatting Date and Time Conversions)

The following date and time conversion characters are used as suffix along with ‘t’ and ‘T’ for date and time conversion.

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

Example: %tA will result in full name of the day of the week.

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

Conversion Specifier Description
A Full name of the day of the week, like “Sunday”, “Monday”
a Short name of the day of the week, like “Mon”, “Tue”
B Full month name like “January”, “February”.
b Short name of the month like “Jan”, “Feb”.
C Last two digits of the year, starting from 00 to 99
c Date and time formatted as “%ta %tb %td %tT %tZ %tY”, like “Mon Jan 01 16:17:00 CST 2018”
D Date formatted as “%tm/%td/%ty”, like “12/31/17”
d Day represented in two digits with leading zeros where necessary, starting from 01 to 31.
e Day of month represented in two digits, like 1 – 31.
F Date formatted in ISO 8601 format as “%tY-%tm-%td” like “2017-12-31”
H Hour representation in 24 hours format with a leading zero as necessary i.e. 00 – 23.
h Short name of the month like “Jan”, “Feb”.
I Hour represented in 12 hour format, formatted as two digits with a leading zero as necessary, i.e. 01 – 12.
j Day of the year out of 366 days (considering leap year), represented with leading 0s i.e. “001” to “366”.
k Hour representation in 24 hour format without a leading 0 starting from “0” to “23”.
l Hour representation in 12-hour format without a leading 0 like “1” to “12”.
L Millisecond within the second formatted represented in three digits with leading zeros starting from 000 to 999.
M Minute within the hour formatted leading zero starting from “00” to “59”.
m Month formatted with a leading zero like “01” to “12”.
N Nanosecond with in the second represented in 9 digits and leading 0s like “000000000” to “999999999”.
p Locale specific morning or afternoon specifier like “am” or “pm” marker.
Q Milliseconds since the start of epoch Jan 1 , 1970 00:00:00 UTC.
R Time represented in 24-hours format i.e. “%tH:%tM” like “20:00”
r Time represented,in 12-hours format i.e “%tI:%tM:%tS %Tp”.
S Seconds within the minute represented in 2 digits like “00” to “60”. “60” is required to support leap seconds.
s Seconds since the start of epoch Jan 1, 1970 00:00:00 UTC.
T Time represented in 24 hours format along with seconds as “%tH:%tM:%tS”
Y Year represented in four digits starting from,”0000″ to “9999”
y Year represented in two digits starting from “00” to “99”
Z Time zone representation in string like “IST”, “CST” etc.
z Numeric time zone offset based on RFC 822 like “-0530”
转换说明符 描述
一个 星期几的全名,例如“星期日”,“星期一”
一个 星期几的简称,例如“ Mon”,“ Tue”
完整的月份名称,例如“一月”,“二月”。
b 月份的简称,例如“ Jan”,“ Feb”。
C 年份的后两位数字,从00到99
C 日期和时间格式为“%ta%tb%td%tT%tZ%tY”,如“ Mon Jan 01 16:17:00 CST 2018”
d 日期格式为“%tm /%td /%ty”,例如“ 12/31/17”
d 从01到31开始,以两位数字表示的日期(必要时以前导零表示)。
Ë 一个月中的一天用两位数字表示,例如1 – 31。
F 日期以ISO 8601格式格式化为“%tY-%tm-%td”,例如“ 2017-12-31”
H 小时制以24小时格式表示,必要时以0开头。
H 月份的简称,例如“ Jan”,“ Feb”。
一世 小时以12小时格式表示,格式为两位数字,必要时以前导零表示,即01 – 12。
Ĵ 366天中的一年中的某天(考虑leap年),以0开头,即“ 001”至“ 366”。
ķ 24小时制的小时表示形式,从“ 0”到“ 23”之间没有前导0。
以12小时格式表示小时,没有前导0,例如“ 1”到“ 12”。
大号 第二个格式中的毫秒以三位数字表示,前导零从000到999开始。
中号 格式化后的小时数,以分钟开头,从“ 00”到“ 59”开始。
月份格式前导零,例如“ 01”到“ 12”。
ñ 纳秒,秒中用9位数字表示,前导0如“ 000000000”至“ 999999999”。
p 特定于语言环境的上午或下午说明符,例如“ am”或“ pm”标记。
自1970年1月1日UTC时间开始以来的毫秒数。
[R 时间以24小时制表示,即“%tH:%tM”,例如“ 20:00”
[R 以12小时格式表示的时间,即“%tI:%tM:%tS%Tp”。
小号 分钟内的秒数用2位数字表示,例如“ 00”至“ 60”。 需要60来支持required秒。
s 自1970年1月1日UTC时间开始以来的秒数。
Ť 时间以24小时格式表示,并以秒表示为“%tH:%tM:%tS”
ÿ 以“ 0000”至“ 9999”开头的四位数表示年份
ÿ 年份以两位数字表示,从“ 00”到“ 99”
ž 时区表示形式,例如“ IST”,“ CST”等
ž 基于RFC 822的数字时区偏移,例如“ -0530”

Java字符串格式宽度 (Java String Format Width)

The minimum number of characters required as the output is considered as the width. An exception will be thrown for line separator conversion as width is not applicable or it.

输出所需的最少字符数被视为宽度。 对于行分隔符转换,将引发异常,因为宽度不适用或不适用。

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

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

Output:

输出:

{      2017}
{        Hello Format}
           

Java字符串格式精度 (Java String Format Precision)

Precision is the maximum number of characters to be written to the output for integer and String.

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

The floating-point conversions ‘a’, ‘A’, ‘e’, ‘E’, and ‘f’ have precision as the number of digits after the decimal. If the conversion is ‘g’ or ‘G’, then the precision is the total number of digits in the resulting magnitude after rounding.

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

An exception is thrown for character, integral, and date/time argument types and the percent and line separator conversions as precision is not applicable for these types.

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

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

System.out.print(s);
           

Output:

输出:

{Hello Fo}
           

Java字符串格式参数索引 (Java String Format Argument Index)

The argument index is a decimal integer starting after “%” sign and ending with “$” sign. The position of the argument in the argument list is decided based on the value of the integer.

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

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

Output:

输出:

{c b a}
           

其他字符串格式化示例 (Miscellaneous String Formatting Examples)

Till now we have observed the various conversion specifiers and the usage of them. In this last section let us check some additional miscellaneous conversions.

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

  1. Left alignment of a text.

    文本的左对齐。

  2. String s = String.format ("{%4s}", "a");
    System.out.print(s);
               

    Output:

    输出:

    {   a}
               
  3. Right alignment of a text.

    文本的右对齐。

  4. String s = String.format ("{%-4s}", "a");
    System.out.print(s);
               

    Output:

    输出:

    {a   }
               
  5. Locale specific number format representation.

    特定于语言环境的数字格式表示形式。

  6. String s = String.format ("{%,d}", 1000000);
    System.out.print(s);
               

    Output:

    输出:

    {1,000,000}
               
  7. Padding with zero.

    填充为零。

  8. String s = String.format ("{%05d}", 99);
    System.out.print(s);
               

    Output:

    输出:

    {00099}
               

That’s all for Java String format examples, for more information on java string format please visit Formatter API Doc.

Java字符串格式示例仅此而已,有关Java字符串格式的更多信息,请访问Formatter API Doc 。

翻译自: https://www.journaldev.com/17850/java-string-format