String.format() 圖文詳解,寫得非常好!

Java技術(shù)棧
www.javastack.cn
關(guān)注閱讀更多優(yōu)質(zhì)文章
引言
String類的format()方法用于創(chuàng)建格式化的字符串以及連接多個(gè)字符串對(duì)象。熟悉C語言應(yīng)該記得C語言的sprintf()方法,兩者有類似之處。
format()方法有兩種重載形式。
重載
// 使用當(dāng)前本地區(qū)域?qū)ο螅↙ocale.getDefault()),制定字符串格式和參數(shù)生成格式化的字符串
String String.format(String fmt, Object... args);
// 自定義本地區(qū)域?qū)ο?,制定字符串格式和參?shù)生成格式化的字符串
String String.format(Locale locale, String fmt, Object... args);
占位符
格式化說明最多會(huì)有5個(gè)部分(不包括%符號(hào)) . 下面的[]符號(hào)里面都是選擇性的項(xiàng)目,因此只有%與type是必要的. 格式化說明的順序是有規(guī)定的,必須要以這個(gè)順序章指定.

實(shí)例:

超過一項(xiàng)以上的參數(shù)時(shí)
把新的參數(shù)加到后面,因此會(huì)有3個(gè)參數(shù)來調(diào)用format()而不是兩個(gè),并且在第一個(gè)參數(shù)中,也就是格式化串中,會(huì)有兩個(gè)不同的格式化設(shè)定,也就是兩個(gè)%開頭的字符組合,第二個(gè)會(huì)應(yīng)用在第一個(gè)%上面,第三個(gè)參數(shù)會(huì)用在第二%上,也就是參數(shù)會(huì)依照順序應(yīng)用在%上面" 。
int one = 123456789;
double two = 123456.789;
String s = String.format("第一個(gè)參數(shù):%,d 第二個(gè)參數(shù):%,.2f", one, two);
System.out.println(s);

轉(zhuǎn)換符

轉(zhuǎn)換符的標(biāo)志

對(duì)字符串進(jìn)行格式化
示例——將"hello"格式化為"hello ?"(左對(duì)齊)
String raw = "hello word";
String str = String.format("|%-15s|", raw);
System.out.println(str);

對(duì)整數(shù)進(jìn)行格式化
示例——將-1000顯示為(1,000)
int num = -1000;String str = String.format("%(,d", num);
System.out.println(str);

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

對(duì)日期時(shí)間進(jìn)行格式化
日期的轉(zhuǎn)換符

時(shí)間的轉(zhuǎn)換符

實(shí)例
Date date = new Date();
System.out.printf("全部日期和時(shí)間信息:%tc%n",date);
System.out.printf("年-月-日格式:%tF%n",date);
System.out.printf("月/日/年格式:%tD%n",date);
System.out.printf("HH:MM:SS PM格式(12時(shí)制):%tr%n",date);
System.out.printf("HH:MM:SS格式(24時(shí)制):%tT%n",date);
System.out.printf("HH:MM格式(24時(shí)制):%tR",date);

點(diǎn)擊「閱讀原文」獲取面試題大全~
評(píng)論
圖片
表情
