public static String pad ( String pSource , int pRequiredLength , String pPadString , boolean pPrepend ) { if ( pPadString == null || pPadString . length ( ) == 0 ) { throw new IllegalArgumentException ( "Pad string: \"" + pPadString + "\"" ) ; } if ( pSource . length ( ) >= pRequiredLength ) { return pSource ; } // TODO: Benchmark the new version against the old one, to see if it's really faster // Rewrite to first create pad // - pad += pad; - until length is >= gap // then append the pad and cut if too long int gap = pRequiredLength - pSource . length ( ) ; StringBuilder result = new StringBuilder ( pPadString ) ; while ( result . length ( ) < gap ) { result . append ( result ) ; } if ( result . length ( ) > gap ) { result . delete ( gap , result . length ( ) ) ; } return pPrepend ? result . append ( pSource ) . toString ( ) : result . insert ( 0 , pSource ) . toString ( ) ; /* StringBuilder result = new StringBuilder(pSource); // Concatenation until proper string length while (result.length() < pRequiredLength) { // Prepend or append if (pPrepend) { // Front result.insert(0, pPadString); } else { // Back result.append(pPadString); } } // Truncate if (result.length() > pRequiredLength) { if (pPrepend) { result.delete(0, result.length() - pRequiredLength); } else { result.delete(pRequiredLength, result.length()); } } return result.toString(); */ }
String length check with simple concatenation of selected pad - string . E . g . a zip number from 123 to the correct 0123 .