java pad string left right - String.format() method


String.format() can be used to left/right pad a given string.
public static String padRight(String s, int n) {
     return String.format("%1$-" + n + "s", s);  }
public static String padLeft(String s, int n) {
    return String.format("%1$#" + n + "s", s);  }
...
public static void main(String args[]) throws Exception {
 System.out.println(padRight("Howto", 20) + "*");
 System.out.println(padLeft("Howto", 25) + "*");
}

No comments :

Post a Comment

Your Comment and Question will help to make this blog better...