Total Pageviews

2015/10/14

[Java] String.format

Requirement
If I have multiple string data, each string data include a Chinese character and an amount with string type, ex. 預 and 14.13

This kind of data should be formatted as bellows:







String format rule is:

  • The first Chinese string character should enclose with left and right parenthesis.
  • The second amount string character has fixed 16 spaces.


How-To
You can utilize String.format to fulfill this requirement

format

public static String format(String format,
            Object... args)
Returns a formatted string using the specified format string and arguments.The locale always used is the one returned by Locale.getDefault().
Parameters:
format - A format string
args - Arguments referenced by the format specifiers in the format string. If there are more arguments than format specifiers, the extra arguments are ignored. The number of arguments is variable and may be zero. The maximum number of arguments is limited by the maximum dimension of a Java array as defined by The Java™ Virtual Machine Specification. The behaviour on a null argument depends on the conversion.
Returns:
A formatted string
Throws:
IllegalFormatException - If a format string contains an illegal syntax, a format specifier that is incompatible with the given arguments, insufficient arguments given the format string, or other illegal conditions. For specification of all possible formatting errors, see the Details section of the formatter class specification.
NullPointerException - If the format is null
Since:
1.5
See Also:
Formatter

Sample code:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
    public static void main(String[] args) {
        // The first Chinese string character should enclose with left and right parenthesis.
        // The second amount string character has fixed 16 spaces.
        String strFormat = "(%s)%16s";

        System.out.println(String.format(strFormat, "預", "14.13"));
        System.out.println(String.format(strFormat, "決", "14.34"));
        System.out.println(String.format(strFormat, "預", "0.00"));
        System.out.println(String.format(strFormat, "決", "3.25"));
    }

Reference
[1] https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#format(java.lang.String,%20java.lang.Object...)
[2] http://jax-work-archive.blogspot.tw/2015/02/java-stringformat.html

No comments: