共計 779 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 Java 中,可以使用 String.format()
方法來格式化字符串。該方法使用格式字符串和可選的參數,返回一個格式化后的字符串。
以下是使用 String.format()
方法的一些示例:
- 格式化整數:
int num = 123456;
String formatted = String.format("%d", num);
System.out.println(formatted); // 輸出: 123456
- 格式化浮點數:
double num = 3.14159;
String formatted = String.format("%.2f", num);
System.out.println(formatted); // 輸出: 3.14
- 格式化日期:
import java.util.Date;
Date now = new Date();
String formatted = String.format("%tF", now);
System.out.println(formatted); // 輸出: 2022-01-01
- 格式化字符串:
String name = "John";
int age = 30;
String formatted = String.format("My name is %s and I'm %d years old.", name, age);
System.out.println(formatted); // 輸出: My name is John and I'm 30 years old.
格式字符串中的占位符可以使用不同的格式說明符來指定所需的格式,例如 %d
表示整數,%.2f
表示帶兩位小數的浮點數,%s
表示字符串等。
此外,還有其他格式說明符可供選擇,例如 %tF
表示完整的日期格式,%tH:%tM:%tS
表示小時、分鐘和秒等。
希望以上示例能幫助您了解如何使用 String.format()
方法進行字符串格式化。
丸趣 TV 網 – 提供最優質的資源集合!
正文完