JAVA字符串格式化——String.format()的使用


引言
String類的format()方法用於創建格式化的字符串以及連接多個字符串對象。熟悉C語言應該記得C語言的sprintf()方法,兩者有類似之處。format()方法有兩種重載形式。

重載
// 使用當前本地區域對象(Locale.getDefault()),制定字符串格式和參數生成格式化的字符串
String String.format(String fmt, Object... args);

// 自定義本地區域對象,制定字符串格式和參數生成格式化的字符串
String String.format(Locale locale, String fmt, Object... args);
占位符
格式化說明最多會有5個部分(不包括%符號) . 下面的[]符號里面都是選擇性的項目,因此只有%與type是必要的. 格式化說明的順序是有規定的,必須要以這個順序章指定.

 

實例:

 

超過一項以上的參數時
把新的參數加到后面,因此會有3個參數來調用format()而不是兩個,並且在第一個參數中,也就是格式化串中,會有兩個不同的格式化設定,也就是兩個%開頭的字符組合,第二個會應用在第一個%上面,第三個參數會用在第二%上,也就是參數會依照順序應用在%上面" 。

int one = 123456789;
double two = 123456.789;
String s = String.format("第一個參數:%,d 第二個參數:%,.2f", one, two);
System.out.println(s);


轉換符


轉換符的標志


對字符串進行格式化
示例——將"hello"格式化為"hello  "(左對齊)

String raw = "hello word";
String str = String.format("|%-15s|", raw);
System.out.println(str);


對整數進行格式化
示例——將-1000顯示為(1,000)

int num = -1000;
String str = String.format("%(,d", num);
System.out.println(str);


對浮點數進行格式化
double num = 123.456789;
System.out.print(String.format("浮點類型:%.2f %n", num));
System.out.print(String.format("十六進制浮點類型:%a %n", num));
System.out.print(String.format("通用浮點類型:%g ", num));


對日期時間進行格式化
日期的轉換符

時間的轉換符

實例

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);

 

 

作者:潘佳琦
鏈接:https://segmentfault.com/a/1190000019350486?utm_source=tag-newest
來源:SegmentFault 思否
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM