Java code for wrapping text lines to a max line width

Apache commons has WordUtils and wrap function in it:

http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/text/WordUtils.html

P.S. Looks like this is deprecated and you need to use

https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/WordUtils.html

instead.


Here's my take

private static final String LINEBREAK = "\n"; // or "\r\n";

public static String wrap(String string, int lineLength) {
    StringBuilder b = new StringBuilder();
    for (String line : string.split(Pattern.quote(LINEBREAK))) {
        b.append(wrapLine(line, lineLength));
    }
    return b.toString();
}

private static String wrapLine(String line, int lineLength) {
    if (line.length() == 0) return LINEBREAK;
    if (line.length() <= lineLength) return line + LINEBREAK;
    String[] words = line.split(" ");
    StringBuilder allLines = new StringBuilder();
    StringBuilder trimmedLine = new StringBuilder();
    for (String word : words) {
        if (trimmedLine.length() + 1 + word.length() <= lineLength) {
            trimmedLine.append(word).append(" ");
        } else {
            allLines.append(trimmedLine).append(LINEBREAK);
            trimmedLine = new StringBuilder();
            trimmedLine.append(word).append(" ");
        }
    }
    if (trimmedLine.length() > 0) {
        allLines.append(trimmedLine);
    }
    allLines.append(linebreak);
    return allLines.toString();
}

(This solution strips two spaces to one space (so same fault that @jett has with Apache commons WordUtils)).


Use the word-wrap library (available on Maven Central).

Here's one way to use it:

String text = "hi there how are you going?";
String wrapped = 
  WordWrap.from(text)
    .maxWidth(10)
    .insertHyphens(true) // true is the default
    .wrap();

Output is:

hi there
how are
you going?

The library conserves leading spaces on lines which is one complaint about the behaviour of the Apache commons-lang offering. You can also specify the stringWidth function to get pixel-accurate results when rendering the text.

The library has decent unit test coverage (something to bear in mind when you consider copy and paste of code chunks from the web!).

The Maven dependency is:

<dependency>
  <groupId>com.github.davidmoten</groupId>
  <artifactId>word-wrap</artifactId>
  <version>0.1.9</version>
</dependency>

Be sure to check for a later version.