How can I pad a String in Java?

pvgoddijn picture pvgoddijn · Dec 23, 2008 · Viewed 613.5k times · Source

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.

Answer

RealHowTo picture RealHowTo · Dec 24, 2008

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*