public static String padOrTrim ( String str , int num ) { if ( str == null ) { str = "null" ; } int leng = str . length ( ) ; if ( leng < num ) { StringBuilder sb = new StringBuilder ( str ) ; for ( int i = 0 ; i < num - leng ; i ++ ) { sb . append ( ' ' ) ; } return sb . toString ( ) ; } else if ( leng > num ) { return str . substring ( 0 , num ) ; } else { return str ; } }
Pad or trim so as to produce a string of exactly a certain length .