public static String pad ( String s , int width , boolean rightJustify ) { if ( s . length ( ) >= width ) { return s ; } StringBuilder sbuff = new StringBuilder ( width ) ; int need = width - s . length ( ) ; sbuff . setLength ( need ) ; for ( int i = 0 ; i < need ; i ++ ) { sbuff . setCharAt ( i , ' ' ) ; } if ( rightJustify ) { sbuff . append ( s ) ; } else { sbuff . insert ( 0 , s ) ; } return sbuff . toString ( ) ; }
Create a new string by padding the existing one with blanks to specified width . Do nothing if length is already greater or equal to width .