天天看點

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