Wrap the string after a number of characters word-wise in Java

Solution 1:

You can use Apache-common's WordUtils.wrap().

Solution 2:

Use lastIndexOf instead of indexOf, e.g.

StringBuilder sb = new StringBuilder(s);

int i = 0;
while (i + 20 < sb.length() && (i = sb.lastIndexOf(" ", i + 20)) != -1) {
    sb.replace(i, i + 1, "\n");
}

System.out.println(sb.toString());

This will produce the following output:

A very long string
containing many
many words and
characters.
Newlines will be
entered at spaces.

Solution 3:

You can try the following:

public static String wrapString(String s, String deliminator, int length) {
    String result = "";
    int lastdelimPos = 0;
    for (String token : s.split(" ", -1)) {
        if (result.length() - lastdelimPos + token.length() > length) {
            result = result + deliminator + token;
            lastdelimPos = result.length() + 1;
        }
        else {
            result += (result.isEmpty() ? "" : " ") + token;
        }
    }
    return result;
}

call as wrapString("asd xyz afz","\n",5)