userimage

Pad a String with same constants in Java?

I have some text message which are messed when I display them on the screen.

Now I want to represent it with the fixed length of 20 character by padding it like,

*******some*message*
some*message********
some*message*display

Please suggest!


userimage

The following link has all the details where Apache StringUtils has several methods like leftPad, rightPad, center and repeat.

http://www.jdocs.com/lang/2.1/org/apache/commons/lang/StringUtils.html


public static String padRight(String str, int no) {

     return String.format("%1$-" + no + "str", str);  

}


public static String padLeft(String str, int no) {

    return String.format("%1$" + no + "str", str);  

}


...


public static void main(String args[]) throws Exception {

 System.out.println(padRight("padRight", 20) + "*");

 System.out.println(padLeft("padLeft", 20) + "*");

}

 

output :

     padRight               *

                    padLeft*


Answer is