方式一:String.format (類 C printf 風格)
基本語法
String formatted = String.format("格式字串", 參數1, 參數2, ...);
常用格式化佔位符
| 佔位符 | 說明 | 範例輸出 |
| %s / %S | 字串 / 大寫字串 | "Hello" / "HELLO" |
| %d | 十進位整數 | 123 |
| %f | 浮點數 (預設 6 位小數) | 3.141593 |
| %.2f | 指定 2 位小數 | 3.14 |
| %x / %X | 十六進位小寫/大寫 | ff / FF |
| %tY / %tm / %td | 日期年/月/日 | 2024 / 03 / 15 |
| %n | 平台相關換行符 | \n (Linux) / \r\n (Windows) |
實戰範例:SQL 字串組裝
Date now = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = sdf.format(now);
String sql = String.format(
"INSERT INTO titles VALUES (%d, '%s', '%s', '%s')",
13, "科技", "管理員", time
);
// 結果:INSERT INTO titles VALUES (13, '科技', '管理員', '2024-03-15 14:30:00')
方式二:MessageFormat (JDK 內建、參數索引式)
語法特點
- 使用
{0}, {1} 等索引佔位符
- 單引號需雙寫
'' 才會輸出單引號
- 支援複雜格式:
{0,number,#.##}, {1,date,yyyy-MM-dd}
實戰範例
String sql = MessageFormat.format(
"INSERT INTO titles VALUES ({0}, ''{1}'', ''{2}'', ''{3}'')",
14, "科技", "管理員", time
);
// 結果:INSERT INTO titles VALUES (14, '科技', '管理員', '2024-03-15 14:30:00')
進階格式化語法
// 數字格式
MessageFormat.format("{0,number,#.##}", 3.14159); // "3.14"
MessageFormat.format("{0,number,currency}", 1234.5); // "¥1,234.50" (視 Locale)
// 日期格式
MessageFormat.format("{0,date,yyyy-MM-dd}", new Date()); // "2024-03-15"
// 選擇格式 (複數形式)
MessageFormat.format("{0,choice,0#無|1#一個|1<多個}", count);
兩者對比選擇建議
| 維度 | String.format | MessageFormat |
| 可讀性 | 格式字串與參數分離 | 索引對應直觀 |
| 重複參數 | 需重複傳遞 | 可重複引用同索引 |
| 國際化 | 需自行管理 Locale | 支援 ResourceBundle 整合 |
| 效能 | 略優 | 解析開銷稍大 |
| 適用場景 | 簡單格式化、日誌、SQL | 複雜模板、國際化訊息 |
現代替代方案 (Java 15+)
// 文字區塊 + formatted (Java 15+)
String json = """
{
"id": %d,
"name": "%s",
"time": "%s"
}
""".formatted(13, "科技", time);
// StringTemplate (Java 21 預覽)
String sql = STR."INSERT INTO titles VALUES (\{id}, '\{name}', '\{time}')";
安全提醒
絕不可用字串格式化組裝 SQL,必須使用 PreparedStatement 參數化查詢防止 SQL 注入。本文範例僅示範格式化語法。