首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 字串格式化完全指南:String.format 與 MessageFormat 實戰對比

     編輯:Java 相關知識

方式一: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.formatMessageFormat
可讀性格式字串與參數分離索引對應直觀
重複參數需重複傳遞可重複引用同索引
國際化需自行管理 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 注入。本文範例僅示範格式化語法。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved