Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the default padding character in Java printf?

Tags:

java

printf

If we do System.out.printf("%10s", "1"); by default, the space characters will be added to fill in 10, right? Is there a way to change this?

I know, you can add 0, by specifying 0 before the s, but does printf support anything else?

like image 298
user113454 Avatar asked Apr 03 '12 16:04

user113454


People also ask

How do I use printf() to print a formatted string in Java?

String.format () returns a formatted string. System.out.printf () also prints a formatted string to the console. printf () uses the java.util.Formatter class to parse the format string and generate the output. Let’s look at the available format specifiers available for printf: Note: %n or are used as line separators in printf ().

What are the specifiers in printf () in Java?

Format specifiers include flags, width, precision, and conversion characters in this sequence: Specifiers in the brackets are optional. Internally, printf () uses the java.util.Formatter class to parse the format string and generate the output. Additional format string options can be found in the Formatter Javadoc. 2.2.

How do I change the width of a printf string?

Format specifications for printf and printf-like methods take an optional width parameter. System.out.printf ( "%10d. %25s $%25.2f ", i + 1, BOOK_TYPE [i], COST [i] ); Adjust widths to desired values. First off, don't call someone lazy without know anything about that person.

How to overload the printf method in Java?

Following are the syntaxes available for overloading the printf method in Java. System.out.printf (string); System.out.printf (format, arguments); System.out.printf (locale, format, arguments); The method returns the output stream and it accepts up to three parameters depending on the overloading.


1 Answers

Nope. Space is hard-coded. Here's the snippet of java.util.Formatter source even:

private String justify(String s) {
    if (width == -1)
    return s;
    StringBuilder sb = new StringBuilder();
    boolean pad = f.contains(Flags.LEFT_JUSTIFY);
    int sp = width - s.length();
    if (!pad)
    for (int i = 0; i < sp; i++) sb.append(' ');
    sb.append(s);
    if (pad)
    for (int i = 0; i < sp; i++) sb.append(' ');
    return sb.toString();
}

If you're looking to get a different padding you could do a post-format replace or something similar:

System.out.print(String.format("%10s", "1").replace(' ', '#'));
like image 100
ɲeuroburɳ Avatar answered Oct 19 '22 17:10

ɲeuroburɳ