Mar 05

Often we need to left or right pad a string, for example when you need a set of strings to be all the same length.

Java introduced Formatter class in 1.5 to provide printf style formatting. We can use this formatting to pad our Strings with spaces. The String class provides a utility format() method that supports this formatting as shown in the following example methods.

public static String rightPad(String s, int width) {
     return String.format("%1$-" + width + "s", s);  
}

public static String leftPad(String s, int width) {
    return String.format("%1$#" + width + "s", s);  
}

written by objects \\ tags: , , , , ,