เมธอด String.format() ของคลาส java.lang.String รับ format string และอาร์กิวเมนต์ แล้วคืนค่าสตริงที่จัดรูปแบบแล้ว (ไม่ได้พิมพ์ออกมาตรงๆ เหมือน printf)
ตัวอย่าง 1: จัดรูปแบบวันที่
import java.util.Calendar;
import java.util.GregorianCalendar;
public class Test {
public static void main(String args[]) {
Calendar cal = GregorianCalendar.getInstance();
System.out.println("Date: " + cal.get(Calendar.DATE));
System.out.println("Month: " + cal.get(Calendar.MONTH));
System.out.println("Year: " + cal.get(Calendar.YEAR));
Object arr[] = { "Date", cal };
System.out.println("Desired Format: ");
// %1$s = อาร์กิวเมนต์ตัวที่ 1 (String), %2$tY = ปีของอาร์กิวเมนต์ตัวที่ 2 (Calendar)
System.out.println(String.format("%1$s = %2$tY %2$tm %2$te", arr));
}
}
ผลลัพธ์
Date: 7 Month: 10 Year: 2020 Desired Format: Date = 2020 11 7
ตัวอย่าง 2: พิมพ์จำนวนเต็มพร้อมเลข 0 นำหน้า (Zero Padding)
public class Demo {
public static void main(String []args) {
int val = 1254;
// %07d = จำนวนเต็ม ความกว้าง 7 ตัวอักษร เติม 0 นำหน้า
String str = String.format("%07d", val);
System.out.println(str);
}
}
ผลลัพธ์
0001254
ตัวอย่าง 3: Format Specifiers สำหรับทุกชนิดข้อมูล
public class Demo {
public static void main(String []args) {
String str = String.format("%d", 245); // Integer
System.out.println(str);
str = String.format("%s", "Welcome to Tutorialspoint"); // String
System.out.println(str);
str = String.format("%f", 126.54); // Float/Double
System.out.println(str);
str = String.format("%c", 't'); // Character
System.out.println(str);
}
}
ผลลัพธ์
245 Welcome to Tutorialspoint 126.540000 t
Format Specifiers สำคัญที่ควรจำ
| Specifier | ประเภทข้อมูล | คำอธิบาย |
|---|---|---|
%d | Integer (byte, short, int, long) | จำนวนเต็ม |
%f | Float, Double | ทศนิยม 6 ตำแหน่ง default |
%.2f | Float, Double | ทศนิยม 2 ตำแหน่ง |
%s | String, Object | สตริง (toString()) |
%c | char, Character | ตัวอักษรเดียว |
%b | Boolean | true/false |
%x | Integer | Hexadecimal (lowercase) |
%X | Integer | Hexadecimal (uppercase) |
%e | Float, Double | Scientific notation |
%% | - | พิมพ์เครื่องหมาย % |
Index References (1$, 2$, ...)
เหมือน printf() สามารถใช้อาร์กิวเมนต์ซ้ำได้ด้วย index:
String formatted = String.format("Name: %1$s, Age: %2$d, Again Name: %1$s", "John", 25);
// ผลลัพธ์: Name: John, Age: 25, Again Name: John
ความแตกต่าง printf() vs String.format()
| คุณสมบัติ | printf() | String.format() |
|---|---|---|
| คืนค่า | PrintStream (void) | String |
| การใช้งาน | พิมพ์ออก Console | เก็บในตัวแปร ส่งต่อได้ |
| Performance | เร็วกว่าเล็กน้อย | สร้าง String object ใหม่ |