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?
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 ().
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.
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.
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.
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(' ', '#'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With