JRJC - How To Format Text

I have a method I created a long time ago called leftText() that solves most of my formatting needs. It will force text to be a specified length by padding spaces to the right. Example

    String s = "Gertrude" ;
    s = leftText( s , 15 );  // s is now set to "Gertrude       "

so if I'm reading a database, I can make an output line like this

    System.out.println( leftText( firstName , 15 ) + leftText( lastName , 20 ) + leftText( city , 20 ) );

and see

    Gertrude       Getrude             Denver
    Ferdinand      Futz                Seattle
    Justin         Case                Portland
    Adam           Baum                Butte

leftText() works great for left justification. I use rightText() for right justification.

My leftText() method has a lot of other baggage, but here is one that can get you started. It could use a lot of improvement, but it will work fine for now:

    static String leftText( String s , int newLen )
        while ( s.length() < newLen )
            s += " ";
        return s ;

If speed is important to you, the first thing you would want to change is to use a StringBuffer as temporary storage ....

© 2000 Paul Wheaton