public String wrap ( String text ) { StringBuilder sb = new StringBuilder ( ) ; int continuationLength = continuation . length ( ) ; int currentPosition = 0 ; for ( String word : text . split ( " " ) ) { String lastWord ; int wordLength = word . length ( ) ; if ( currentPosition + wordLength <= width ) { if ( currentPosition != 0 ) { sb . append ( " " ) ; currentPosition += 1 ; } sb . append ( lastWord = word ) ; currentPosition += wordLength ; } else { if ( currentPosition > 0 ) { sb . append ( LINE_SEPARATOR ) ; currentPosition = 0 ; } if ( wordLength > width && strict ) { int i = 0 ; while ( i + width < wordLength ) { sb . append ( word . substring ( i , width - continuationLength ) ) . append ( continuation ) . append ( LINE_SEPARATOR ) ; i += width - continuationLength ; } String endOfWord = word . substring ( i ) ; sb . append ( lastWord = endOfWord ) ; currentPosition = endOfWord . length ( ) ; } else { sb . append ( lastWord = word ) ; currentPosition += wordLength ; } } int lastNewLine = lastWord . lastIndexOf ( "\n" ) ; if ( lastNewLine != - 1 ) { currentPosition = lastWord . length ( ) - lastNewLine ; } } return sb . toString ( ) ; }
Wrap the specified text .