溫馨提示×

String.format怎樣格式化字符串

小樊
81
2024-10-12 10:36:06
欄目: 編程語言

String.format() 是 Java 中的一個(gè)非常有用的方法,用于格式化字符串。它允許你使用占位符 {} 來表示要插入的值,并通過傳遞參數(shù)來替換這些占位符。以下是一些基本的使用示例:

  1. 基本格式化
String name = "Alice";
int age = 30;
String formattedString = String.format("My name is %s and I am %d years old.", name, age);
System.out.println(formattedString);  // 輸出:My name is Alice and I am 30 years old.

在這個(gè)例子中,%s 是一個(gè)字符串占位符,%d 是一個(gè)整數(shù)占位符。 2. 格式化浮點(diǎn)數(shù)

double pi = 3.14159;
String formattedDouble = String.format("Pi is approximately %.2f.", pi);
System.out.println(formattedDouble);  // 輸出:Pi is approximately 3.14.

在這里,%.2f 表示保留兩位小數(shù)的浮點(diǎn)數(shù)。 3. 對齊和填充

int[] numbers = {1, 2, 3, 4, 5};
String formattedArray = String.format("%-5d | %-5d | %-5d | %-5d | %-5d", numbers[0], numbers[1], numbers[2], numbers[3], numbers[4]);
System.out.println(formattedArray);
// 輸出(假設(shè)數(shù)字寬度至少為5):
// 1     | 2     | 3     | 4     | 5    

在這個(gè)例子中,%-5d 表示左對齊的數(shù)字,總寬度為5個(gè)字符。如果數(shù)字不足5個(gè)字符,它會(huì)在左側(cè)用空格填充。 4. 使用換行符

String multiLineString = String.format("Hello, %s!\nToday is %s.", "World", "Monday");
System.out.println(multiLineString);
// 輸出:
// Hello, World!
// Today is Monday.

注意,\n 在字符串字面值中表示換行符,但在 String.format() 中不是必需的,除非你確實(shí)想在格式化的字符串中包含換行。 5. 類型轉(zhuǎn)換

String.format() 還支持一些類型轉(zhuǎn)換,如將整數(shù)轉(zhuǎn)換為十六進(jìn)制字符串:

int number = 255;
String hexString = String.format("The hexadecimal value of %d is %X.", number, number);
System.out.println(hexString);  // 輸出:The hexadecimal value of 255 is FF.

在這個(gè)例子中,%X 表示大寫的十六進(jìn)制表示。如果你想要小寫,可以使用 %x

0