| 方法 | 描述 |
|---|---|
| static String format(Locale l, String format, Object... args) static String format(String format, Object... args) | 格式化字串 |
舉例如下
class FormatDemo {
public static void main(String[] args) {
String a = "%s is more important than %s.";
String b = "He who has hope has everything.";
String c = "台上 %d 分鐘,台下 %d 年功。";
System.out.println(String.format(a, "Imagination", "knowledge"));
System.out.println(String.format(b, "everything"));
System.out.println(String.format(c, 1, 10));
}
}
/* 《程式語言教學誌》的範例程式
http://pydoing.blogspot.com/
檔名:ConcatDemo.java
功能:示範物件導向的基本觀念
作者:張凱慶
時間:西元 2010 年 10 月 */編譯後執行,結果如下

所謂的格式化字串像是
String a = "%s is more important than %s."; String b = "He who has hope has everything."; String c = "台上 %d 分鐘,台下 %d 年功。";
其中像是 %s 、 %d 等都是轉換字符,凡是有轉換字符的地方,在 format() 都需要提供相對應的參數 (parameter)
System.out.println(String.format(a, "Imagination", "knowledge")); System.out.println(String.format(b, "everything")); System.out.println(String.format(c, 1, 10));
格式化字串 a 有兩個轉換字符,因此其後需提供兩個相對應型態的參數, %s 表示字串,所以參數的型態必須是字串。同樣的, b 有一個轉換字符為 %s , c 有兩個轉換字符 %d ,這表示整數,因此需要額外的兩個整數型態的參數。
常見轉換字符如下列表
| 轉換字符 | 說明 |
|---|---|
| 'b', 'B' | 真假值 |
| 'h', 'H' | 雜湊碼 |
| 's', 'S' | 字串 |
| 'c', 'C' | 字元 |
| 'd' | 十進位整數 |
| 'o' | 八進位整數 |
| 'x', 'X' | 十六進位整數 |
| 'e', 'E' | 科學記號浮點數 |
| 'f' | 十進位浮點數 |
| 'g', 'G' | 科學記號浮點數 |
| 'a', 'A' | 十六進位浮點數 |
| 't', 'T' | 日期時間 |
| '%' | 百分比符號 |
| 'n' | 換行符號 |
| 中英文術語對照 | |
|---|---|
| 類別 | class |
| 方法 | method |
| 字串 | string |
| 參數 | parameter |
參考資料
http://download.oracle.com/javase/tutorial/java/data/strings.html
http://download.oracle.com/javase/tutorial/java/data/converting.html
http://download.oracle.com/javase/tutorial/java/data/manipstrings.html
http://download.oracle.com/javase/tutorial/java/data/comparestrings.html
http://download.oracle.com/javase/7/docs/api/java/lang/String.html
http://download.oracle.com/javase/tutorial/java/data/strings.html
http://download.oracle.com/javase/tutorial/java/data/converting.html
http://download.oracle.com/javase/tutorial/java/data/manipstrings.html
http://download.oracle.com/javase/tutorial/java/data/comparestrings.html
http://download.oracle.com/javase/7/docs/api/java/lang/String.html
沒有留言:
張貼留言