Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

การใช้ String.format() ใน Java


เมธอด 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ประเภทข้อมูลคำอธิบาย
%dInteger (byte, short, int, long)จำนวนเต็ม
%fFloat, Doubleทศนิยม 6 ตำแหน่ง default
%.2fFloat, Doubleทศนิยม 2 ตำแหน่ง
%sString, Objectสตริง (toString())
%cchar, Characterตัวอักษรเดียว
%bBooleantrue/false
%xIntegerHexadecimal (lowercase)
%XIntegerHexadecimal (uppercase)
%eFloat, DoubleScientific 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 ใหม่