EN
Java - padding left string or number with String.format()
4
points
In this short article, we would like to show how in Java, pad left indicated string or number using String.format()
method.
Quick solution:
System.out.println(String.format("%10s", 123)); // 123
System.out.println(String.format("%13s", "abc")); // abc
or:
// 7 +3 = 10
// vvvvvvvxxx
System.out.println(String.format("%1$10s", 123)); // 123
// 10 +3 = 13
// vvvvvvvvvvxxx
System.out.println(String.format("%1$13s", "abc")); // abc
Where:
10
and13
represent returned minimal string size (spaces + argument) (used in%10s
,%13s
,%1$10s
and%1$13s
).
e.g.123
andabc
.1
indicates used argument number (used in%1$10s
and%1$13s
).
Explaination
Arguments addressing:
- using arguments order:
String.format("%10s %10s %10s", a, b, c)
Where: each
%10s
will printa
,b
andc
variables in provided order using 10 characters (spaces + argument). -
using an indicated index:
System.out.println(String.format("%1$10s / %2$10s / %2$10s", a, b));
Where:
%1
and%2
indicate used argument number,$10s
indicates 10 characters (spaces + argument).
Practical example
We can indicate any number of the arguments addressing the same arguments multiple times in String.format()
method.
public class Example {
public static void main(String []args) {
System.out.println(String.format("%10s", 123)); // 123
System.out.println(String.format("%10s", "abc")); // abc
// accessing by used order
// used: argument 1, agrument 2
System.out.println(String.format("%10s / %10s", 5, 50)); // 5 / 50
// accessing by indicated index
// used: argument 1, agrument 2, argument 2
System.out.println(String.format("%1$10s / %2$10s / %2$10s", 1, 2)); // 1 / 2 / 2
}
}