冰楓論壇

標題: [原創簡短教學]Java 21 字符串模板教學 [打印本頁]

作者: 0dayshare02    時間: 2023-9-21 11:56
標題: [原創簡短教學]Java 21 字符串模板教學
Java 21帶來了許多新特性,其中最受開發者歡迎的就是字符串模板。在過去,我們經常使用String.format或StringBuilder來組合和格式化字符串。但在Java 21中,字符串模板提供了一種更簡潔、更直觀的方法來完成這些操作。本教學將指導您如何使用這一新特性,並提供相關的例子進行說明。



1. 什麼是字符串模板?

字符串模板是Java 21中的新特性,允許開發者在字符串字面量中直接插入變量或表達式的值,而無需使用額外的方法或操作。

2. 如何使用字符串模板?

使用字符串模板非常簡單。您只需使用三個雙引號(""")來定義一個字符串模板,然後在其中使用%s(或其他格式指定符)來插入變量或表達式的值。

例子:
  1. String name = "Alice";
  2. String greeting = """Hello, %s!""".formatted(name);
  3. System.out.println(greeting);  // 輸出: Hello, Alice!
複製代碼
3. 字符串模板的優勢

簡潔性:不再需要冗長的String.format或StringBuilder操作。
可讀性:代碼更加直觀,易於理解。
靈活性:可以輕鬆插入多個變量或表達式。

4. 實際應用

a. 創建JSON字符串

在JDK 21之前,我們可能會這樣做:
  1. String fruit = "apple";
  2. String color = "red";
  3. String json = String.format("{\"fruit\": \"%s\", \"color\": \"%s\"}", fruit, color);
複製代碼
使用字符串模板,我們可以這樣做:
  1. String fruit = "apple";
  2. String color = "red";
  3. String json = """{
  4.     "fruit": "%s",
  5.     "color": "%s"
  6. }""".formatted(fruit, color);
複製代碼
b. 創建HTML內容

在JDK 21之前:
  1. String title = "Welcome";
  2. String content = String.format("<h1>%s</h1>", title);
複製代碼
使用字符串模板:
  1. String title = "Welcome";
  2. String content = """<h1>%s</h1>""".formatted(title);
複製代碼
希望這篇教學能幫助您更好地理解和使用Java 21中的字符串模板特性。







歡迎光臨 冰楓論壇 (https://bingfong.com/) Powered by 冰楓