public static String wrap ( String line , int widthInCharacters , String indent ) { StringBuilder buffer = new StringBuilder ( ) ; int lineCount = 1 ; int spaceIndex ; // if indent is null, then do not indent the wrapped lines indent = ( indent != null ? indent : EMPTY_STRING ) ; while ( line . length ( ) > widthInCharacters ) { spaceIndex = line . substring ( 0 , widthInCharacters ) . lastIndexOf ( SINGLE_SPACE ) ; buffer . append ( lineCount ++ > 1 ? indent : EMPTY_STRING ) ; // throws IndexOutOfBoundsException if spaceIndex is -1, implying no word boundary was found within // the given width; this also avoids the infinite loop buffer . append ( line . substring ( 0 , spaceIndex ) ) ; buffer . append ( LINE_SEPARATOR ) ; // possible infinite loop if spaceIndex is -1, see comment above line = line . substring ( spaceIndex + 1 ) ; } buffer . append ( lineCount > 1 ? indent : EMPTY_STRING ) ; buffer . append ( line ) ; return buffer . toString ( ) ; }
Wraps a line of text to no longer than the specified width measured by the number of characters in each line indenting all subsequent lines with the indent . If the indent is null then an empty String is used .