How can I pad a String in Java?
Is there some easy way to pad Strings in Java?
Seems like something that should be in some StringUtil-like API, but I can't find anything that does this.
Solution 1:
Since Java 1.5, String.format()
can be used to left/right pad a given string.
public static String padRight(String s, int n) {
return String.format("%-" + n + "s", s);
}
public static String padLeft(String s, int n) {
return String.format("%" + n + "s", s);
}
...
public static void main(String args[]) throws Exception {
System.out.println(padRight("Howto", 20) + "*");
System.out.println(padLeft("Howto", 20) + "*");
}
And the output is:
Howto *
Howto*
Solution 2:
Padding to 10 characters:
String.format("%10s", "foo").replace(' ', '*');
String.format("%-10s", "bar").replace(' ', '*');
String.format("%10s", "longer than 10 chars").replace(' ', '*');
output:
*******foo
bar*******
longer*than*10*chars
Display '*' for characters of password:
String password = "secret123";
String padded = String.format("%"+password.length()+"s", "").replace(' ', '*');
output has the same length as the password string:
secret123
*********
Solution 3:
Apache StringUtils
has several methods: leftPad
, rightPad
, center
and repeat
.
But please note that — as others have mentioned and demonstrated in this answer — String.format()
and the Formatter
classes in the JDK are better options. Use them over the commons code.
Solution 4:
In Guava, this is easy:
Strings.padStart("string", 10, ' ');
Strings.padEnd("string", 10, ' ');