作者:潘佳琦
鏈接:https://segmentfault.com/a/1190000019350486
引言
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);

近期熱文推薦:
1.免費獲取 IntelliJ IDEA 激活碼的 6 種方式!
2.我用 Java 8 寫了一段邏輯,同事直呼看不懂,你試試看,,
3.吊打 Tomcat ,Undertow 性能很炸!!
4.國人開源了一款超好用的 Redis 客戶端,真香!!
5.《Java開發手冊(嵩山版)》最新發布,速速下載!
覺得不錯,別忘了隨手點贊+轉發哦!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/5959.html
標籤:Java
上一篇:Java例外
