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 == '\n') {
                    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();
    }
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 == '\n' ) { 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.

<p>If you want the text to wrap for a graphical display, use a wordwrapping component
such as {@link com.samskivert.swing.Label} instead.

@param str String to word-wrap.
@param width Maximum line length.