Hướng dẫn sử dụng String Format trong Java

1. Sử dụng System.out.printf

Sử dụng hàm printf() để định dạng chuỗi và hiển thị ra console.

Phương thức:

public void System.out.printf(String format, Object… args)
public void System.out.printf(Locale locale, String format, Object… args)

Trong đó:

  • locale : xác định locale được áp dụng trong phương thức format.
  • format : định dạng của chuỗi.
  • args : tham số trong chuỗi format, có thể không có hoặc có nhiều tham số.

Chuối format theo cấu trúc sau:

"% [argument index] [flag] [width] [.precision] type"

  • % là một ký tự đặc biệt biểu thị rằng một hướng dẫn định dạng sau.
  • [argument index] : xác định chỉ số của các đối số để được định dạng. Nếu không xác định cụ thể, các đối số sẽ được định dạng theo thứ tự như chúng xuất hiện trong danh sách đối số.
  • [flag] là một hướng dẫn định dạng đặc biệt. Ví dụ, cờ + xác định rằng một giá trị số phải luôn luôn được định dạng với một ký hiệu, và cờ 0 chỉ định rằng 0 là ký tự đệm. Các cờ khác bao gồm  đó là pad ở bên phải, + pad ở bên trái (nếu đối tượng được định dạng là một chuỗi). Lưu ý rằng một số cờ không thể được kết hợp với một số cờ khác hoặc với các đối tượng được định dạng nhất định.
  • [width] xác định số lượng tối thiểu các ký tự output cho đối tượng đó.
  • [.precession] xác định chính xác của các số dấu chấm động trong output. Đó là cơ bản số chữ số thập phân bạn muốn in trên đầu ra. Nhưng nó có thể được sử dụng cho các loại khác để cắt giảm chiều rộng đầu ra
  • type : type và % là các tham số định dạng bắt buộc duy nhất. type là kiểu đối tượng sẽ được định dạng trong đầu ra. Đối với các số nguyên d, cho các chuỗi đó là s, cho các số dấu phẩy là f, cho các số nguyên có định dạng hex là x.

Ví dụ:

public class StringFormat {
    public static void main(String[] args) {
        System.out.printf("Integer : %d\n", 15);
        System.out.printf("Floating point number with 3 decimal digits: %.3f \n", 1.21312939123);
        System.out.printf("Floating point number with 8 decimal digits: %.8f \n", 1.21312939123);
        System.out.printf("String: %s, integer: %d, float: %.6f \n", "Hello World", 89, 9.231435);
        System.out.printf("Re-order output %4$2s %1$2s %3$2s %2$2s \n", "a", "b", "c", "d");
    }
}


Kết quả:

Integer : 15
Floating point number with 3 decimal digits: 1.213
Floating point number with 8 decimal digits: 1.21312939
String: Hello World, integer: 89, float: 9.231435
Re-order output  d  a  c  b 


2. Quy tắc định dạng chuỗi

2.1. Định dạng kiểu số nguyên (Integer)

  • %d : sẽ in số nguyên như tham số đầu vào.
  • %6d : sẽ in số nguyên như tham số đầu vào. Nếu số chữ số nhỏ hơn 6, đầu ra sẽ được thêm khoảng trắng ở bên trái.
  • %-6d : sẽ in số nguyên như tham số đầu vào. Nếu số chữ số nhỏ hơn 6, đầu ra sẽ được thêm khoảng trắng ở bên phải.
  • %06d : sẽ in số nguyên như tham số đầu vào. Nếu số chữ số nhỏ hơn 6, đầu ra sẽ được thêm ký tự số 0 ở bên trái.
  • %.2d : in tối đa 2 chữ số của số nguyên.

Ví dụ:

public class StringFormat {
    public static void main(String[] args) {
        System.out.printf("%-12s%-12s%s\n","Column 1","Column 2","Column3");
        System.out.printf("%-12d%-12d%07d\n", 15, 12, 5);
    }
}


Kết quả:

Column 1    Column 2    Column3
15          12          0000005


Định dạng kiểu chuỗi (String)

  • %s : sẽ in chuỗi tham số đầu vào.
  • %15s : sẽ in chuỗi như tham số đầu vào. Nếu số chữ số nhỏ hơn 15, đầu ra sẽ được thêm khoảng trắng ở bên trái.
  • %-6s : sẽ in chuỗi như tham số đầu vào. Nếu số chữ số nhỏ hơn 6, đầu ra sẽ được thêm khoảng trắng ở bên phải.
  • %.8s : in tối đa tối chuỗi 8 ký tự.

Ví dụ:

public class StringFormat {
    public static void main(String[] args) {
        System.out.printf("%-12s%-12s%s\n","Column 1","Column 2","Column3");
        System.out.printf("%-12.5s%s", "Hello World","World");
    }
}


Kết quả:

Column 1    Column 2    Column3
Hello       World


Định dạng kiểu số thực (Float)

  • %f : sẽ in số thực như tham số đầu vào.
  • %15f : sẽ in số thực như tham số đầu vào. Nếu số chữ số nhỏ hơn 15, đầu ra sẽ được thêm khoảng trắng ở bên trái.
  • %.8f : hiển thị tối đa 8 chữ số thập phân của số.
  • %9.4f : hiển thị tối đa 4 chữ số thập phân của số. Đầu ra sẽ chiếm ít nhất 9 ký tự. Nếu số chữ số không đủ, nó sẽ được đệm khoảng trắng.

Ví dụ:

public class StringFormat {
    public static void main(String[] args) {
        System.out.printf("%-12s%-12s\n","Column 1","Column 2");
        System.out.printf("%-12.5f%.20f", 12.23429837482,9.10212023134);
    }
}


Kết quả:

Column 1    Column 2   
12.23430    9.10212023134000000000


2.4. Bảng tổng hợp mô tả định dạng chữ, số

Ký hiệuPhạm ví dụngKết quả đầu ra
%afloating point (except BigDecimal)Hex output of floating point number
%bAny type“true” if non-null, “false” if null
%ccharacterUnicode character
%dinteger (incl. byte, short, int, long, bigint)Decimal Integer
%efloating pointdecimal number in scientific notation
%ffloating pointdecimal number
%gfloating pointdecimal number, possibly in scientific notation depending on the precision and value.
%hany typeHex String of value from hashCode() method.
 %nnonePlatform-specific line separator.
%ointeger (incl. byte, short, int, long, bigint)Octal number
%sany typeString value
%tDate/Time (incl. long, Calendar, Date and TemporalAccessor)%t is the prefix for Date/Time conversions. More formatting flags are needed after this. See Date/Time conversion below.
%xinteger (incl. byte, short, int, long, bigint)Hex string.

2.5. Bảng tổng hợp mô tả định dạng ngày giờ (Date time)

Ký hiệuMô tả
%tAFull name of the day of the week, e.g. “Sunday“, “Monday“
%taAbbreviated name of the week day e.g. “Sun“, “Mon“, etc.
%tBFull name of the month e.g. “January“, “February“, etc.
%tbAbbreviated month name e.g. “Jan“, “Feb“, etc.
%tCCentury part of year formatted with two digits e.g. “00” through “99”.
%tcDate and time formatted with “%ta %tb %td %tT %tZ %tY” e.g. “Fri Feb 17 07:45:42 PST 2017“
%tDDate formatted as “%tm/%td/%ty“
%tdDay of the month formatted with two digits. e.g. “01” to “31“.
%teDay of the month formatted without a leading 0 e.g. “1” to “31”.
%tFISO 8601 formatted date with “%tY-%tm-%td“.
%tHHour of the day for the 24-hour clock e.g. “00” to “23“.
%thSame as %tb.
%tIHour of the day for the 12-hour clock e.g. “01” – “12“.
%tjDay of the year formatted with leading 0s e.g. “001” to “366“.
%tkHour of the day for the 24 hour clock without a leading 0 e.g. “0” to “23“.
%tlHour of the day for the 12-hour click without a leading 0 e.g. “1” to “12“.
%tMMinute within the hour formatted a leading 0 e.g. “00” to “59“.
%tmMonth formatted with a leading 0 e.g. “01” to “12“.
%tNNanosecond formatted with 9 digits and leading 0s e.g. “000000000” to “999999999”.
%tpLocale specific “am” or “pm” marker.
%tQMilliseconds since epoch Jan 1 , 1970 00:00:00 UTC.
%tRTime formatted as 24-hours e.g. “%tH:%tM“.
%trTime formatted as 12-hours e.g. “%tI:%tM:%tS %Tp“.
%tSSeconds within the minute formatted with 2 digits e.g. “00” to “60”. “60” is required to support leap seconds.
%tsSeconds since the epoch Jan 1, 1970 00:00:00 UTC.
%tTTime formatted as 24-hours e.g. “%tH:%tM:%tS“.
%tYYear formatted with 4 digits e.g. “0000” to “9999“.
%tyYear formatted with 2 digits e.g. “00” to “99“.
%tZTime zone abbreviation. e.g. “UTC“, “PST“, etc.
%tzTime Zone Offset from GMT e.g. “ -0800 “.

Ví dụ:

import java.util.Calendar;
 
public class StringFormat {
    public static void main(String[] args) {
        Calendar cal = Calendar.getInstance();
        cal.set(2017, 11, 4);
 
        // Format the month.
        System.out.printf("Month: %1$tB %1$tb %1$tm \n", cal);
 
        // Format the day.
        System.out.printf("Day: %1$tA %1$ta %1$td \n", cal);
 
        // Format the year.
        System.out.printf("Year: %1$tY %1$ty %1$tj \n", cal);
         
        // Format the hour.
        System.out.printf("Hour: %1$tH %1$tI %1$tk %1$tl \n", cal);
 
        // Format minute.
        System.out.printf("Minute: %1$tM \n", cal);
 
        // Format the second.
        System.out.printf("Second: %1$tS \n", cal);
 
        // Format the am and pm part.
        System.out.printf("AM/PM: %1$tp \n", cal);
    }
}


Kết quả:

Month: December Dec 12
Day: Monday Mon 04
Year: 2017 17 338
Hour: 16 04 16 4
Minute: 18
Second: 11
AM/PM: pm 


3. Sử dụng String.format

Nếu bạn không muốn in chuỗi ra màn hình (console) và muốn tái sử dụng sau này, bạn có thể sử dụng String.format(). Cách sử dụng cũng giống như printf, tuy nhiên nó không in ra console mà return về chuỗi đã được format.

Phương thức:

public static String format(String format, Object... args)
public static String format(Locale locale, String format, Object... args)


Ví dụ:

public class StringFormat {
    public static void main(String[] args) {
        String header = String.format("%-12s%-12s%s","Column 1","Column 2","Column3");
        String row = String.format("%-12d%-12d%07d", 15, 12, 5);
        System.out.println(header);
        System.out.println(row);
    }
}


Kết quả:

Column 1    Column 2    Column3
15          12          0000005


Có thể kết hợp Formater với StringBuilder/ StringBuffer. Kết quả output của chuỗi được format sẽ tự động appended vào StringBuilder/ StringBuffer.

Ví dụ:

import java.util.Formatter;
 
public class StringFormat {
    public static void main(String[] args) {
        StringBuilder sbuf = new StringBuilder();
        Formatter fmt = new Formatter(sbuf);
        fmt.format("PI = %f%n", Math.PI);
        System.out.print(sbuf.toString());
    }
}


Kết quả:

PI = 3.141593


4. Sử dụng java.text.MessageFormat

MessageFormat cung cấp phương thức để tạo ra các chuỗi được định dạng dựa trên mẫu (pattern) được thiết kế. MessageFormat cũng có tính năng tương tự như phương thức String.format().

MessageFormat lấy một tập hợp các đối tượng, định dạng chúng, sau đó chèn các chuỗi được định dạng vào mẫu ở các vị trí thích hợp.

Phương thức:

public MessageFormat(String pattern);
 
public MessageFormat(String pattern, Locale locale);


Trong đó:

  • pattern: xác định mẫu định dạng.
  • locale: xác định locale được áp dụng trong phương thức format.

Pattern của MessageFormat có cấu trúc như sau:

MessageFormatPattern:
         String
         MessageFormatPattern FormatElement String
 
 FormatElement:
         { ArgumentIndex }
         { ArgumentIndex , FormatType }
         { ArgumentIndex , FormatType , FormatStyle }
 
 FormatType: one of 
         number date time choice
 
 FormatStyle:
         short
         medium
         long
         full
         integer
         currency
         percent
         SubformatPattern


Ví dụ:

import java.text.MessageFormat;
import java.util.Date;
 
public class MessageFormatExample {
 
    public static void main(String[] args) {
 
        int planet = 7;
        String event = "a disturbance in the Force";
        String pattern = "At {1,time} on {1,date}, there was {2} on planet {0,number,integer}.";
 
        String output = MessageFormat.format(pattern, planet, new Date(), event);
        System.out.println(output);
    }
 
}


Kết quả:

At 4:29:21 PM on Nov 4, 2017, there was a disturbance in the Force on planet 7.


Một trường hợp sử dụng rất hay của StringFormat là có thể tách tham số dựa trên chuỗi đã được format.

Ví dụ:

import java.text.MessageFormat;
import java.text.ParsePosition;
 
public class MessageFormatParseExample {
 
    public static void main(String[] args) {
        MessageFormat mf = new MessageFormat("String: {0}\nInteger: {1}\nDouble: {2}");
 
        Object[] objArray = { "This is a string", new Integer(56), new Double(12.34) };
        String message = mf.format(objArray);
 
        System.out.println("The message: \n" + message);
 
        Object[] obj = mf.parse(message, new ParsePosition(0));
 
        System.out.println("\n\nObjects parsed:");
        for (Object o : obj) {
            System.out.println(o + " of " + o.getClass().toString());
        }
 
    }
 
}


Kết quả:

The message: 
String: This is a string
Integer: 56
Double: 12.34
 
 
Objects parsed:
This is a string of class java.lang.String
56 of class java.lang.String
12.34 of class java.lang.String


Trên là hướng dẫn cơ bản về định dạng trong java, rất hữu ích cho việc hiển thị định dạng chuỗi một cách nhanh chóng. Tùy vào yêu cầu thực tế, bạn có thể vận dụng vào trong chương trình của mình.

Cám ơn các bạn đã quan tâm và theo dõi bài viết. Hẹn gặp lại các bạn ở các bài viết tiếp theo.

Related posts:

Java Program to Implement Warshall Algorithm
Spring Boot - Google OAuth2 Sign-In
Java Stream Filter with Lambda Expression
String Joiner trong Java 8
Basic Authentication with the RestTemplate
Java Program to Implement Control Table
Server-Sent Events in Spring
Exploring the Spring Boot TestRestTemplate
How to Get the Last Element of a Stream in Java?
Java Web Services – Jersey JAX-RS – REST và sử dụng REST API testing tools với Postman
So sánh Array và ArrayList trong Java
Vòng lặp for, while, do-while trong Java
Java Program to Represent Graph Using Adjacency Matrix
Java Program to Check whether Graph is a Bipartite using 2 Color Algorithm
Java Program to Check Whether Graph is DAG
Java Program to Implement Best-First Search
Base64 encoding và decoding trong Java 8
Java Program to Implement HashTable API
Spring Security with Maven
Java Program to Implement Traveling Salesman Problem using Nearest neighbour Algorithm
Java Program to Perform Complex Number Multiplication
Java Program to Generate a Random Subset by Coin Flipping
Java Program to Implement Skip List
Java Program to Implement Ford–Fulkerson Algorithm
Transaction Propagation and Isolation in Spring @Transactional
Converting between an Array and a List in Java
Spring Cloud AWS – S3
Từ khóa this và super trong Java
Java Program to Give an Implementation of the Traditional Chinese Postman Problem
Java Program to Find a Good Feedback Edge Set in a Graph
Implementing a Runnable vs Extending a Thread
Overflow and Underflow in Java