public static String wordWrap ( String str , int width ) { int size = str . length ( ) ; StringBuilder buf = new StringBuilder ( size + size / width ) ; int lastidx = 0 ; while ( lastidx < size ) { if ( lastidx + width >= size ) { buf . append ( str . substring ( lastidx ) ) ; break ; } int lastws = lastidx ; for ( int ii = lastidx , ll = lastidx + width ; ii < ll ; ii ++ ) { char c = str . charAt ( ii ) ; if ( c == ' ' ) { buf . append ( str . substring ( lastidx , ii + 1 ) ) ; lastidx = ii + 1 ; break ; } else if ( Character . isWhitespace ( c ) ) { lastws = ii ; } } if ( lastws == lastidx ) { buf . append ( str . substring ( lastidx , lastidx + width ) ) . append ( LINE_SEPARATOR ) ; lastidx += width ; } else if ( lastws > lastidx ) { buf . append ( str . substring ( lastidx , lastws ) ) . append ( LINE_SEPARATOR ) ; lastidx = lastws + 1 ; } } return buf . toString ( ) ; }
Wordwraps a string . Treats any whitespace character as a single character .