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

String Formatting ใน Java: ใช้ % และ String.format()

String Formatting ใน Java

ใช้ String.format() หรือ System.out.printf() กับ Format Specifiers เริ่มด้วย %

ตัวอย่างโค้ด

public class Demo { 
    public static void main(String args[]) { 
        String myStr = " sample."; 
        
        // %s = String
        String concatStr = String.format("This is a%s", myStr); 
        
        // %.4f = Floating point 4 decimal places
        String formatStr = String.format("The value is %.4f", 78.92367); 
        
        System.out.println(concatStr); 
        System.out.println(formatStr); 
    } 
}

ผลลัพธ์

This is a sample.
The value is 78.9237

Format Specifiers พื้นฐาน

Specifierประเภทตัวอย่างผลลัพธ์
%sStringString.format("%s", "hi")hi
%dInteger (decimal)String.format("%d", 42)42
%fFloat/DoubleString.format("%f", 3.14)3.140000
%.2fFloat 2 decimalString.format("%.2f", 3.14159)3.14
%xHex (lowercase)String.format("%x", 255)ff
%XHex (uppercase)String.format("%X", 255)FF
%oOctalString.format("%o", 10)12
%bBooleanString.format("%b", true)true
%cCharacterString.format("%c", 'A')A
%%Percent signString.format("100%%")100%

Flags และ Width/Precision

Syntaxความหมายตัวอย่าง
%10sWidth 10, ชิดขวา"_____hello"
%-10sWidth 10, ชิดซ้าย"hello_____"
%05dWidth 5, เติม 0 นำหน้า"00042"
%+dแสดงเครื่องหมาย +/-"+42", "-5"
%,dComma grouping"1,000,000"
%(dลบในวงเล็บ"(42)"

Date/Time Formatting (Java 8+)

LocalDateTime now = LocalDateTime.now(); 
String formatted = String.format("%tF %tT", now, now); 
// 2024-01-15 14:30:45

// หรือใช้ DateTimeFormatter (แนะนำ)
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); 
String formatted = now.format(fmt);

String.format vs printf vs MessageFormat

MethodUse Case
String.format()สร้าง String object, reusable
System.out.printf()พิมพ์ทันที ไม่ต้องเก็บ String
MessageFormatComplex patterns, i18n, pluralization
StringBuilderPerformance critical, many concatenations