2.10. Wrapping Words

Problem

You want to wrap lines of text using different line widths and various line termination sequences.

Solution

Use WordUtils to wrap words. Supply the number of columns and a line termination string, and WordUtils will wrap text. The following example wraps a small string to 20 columns:

// Define original String
String message = "One Two Three Four Five";

// Wrap the text.
String wrappedString = 
    WordUtils.wrapText( message, 20, "\n", false );

System.out.println( "Wrapped Message:\n\n" + wrappedString );

This produces the following output:

Wrapped Message:

One Two Three Four 
Five

Discussion

When WordUtils wraps a string, it takes a user-supplied line termination sequence like \n or \r\n and inserts this line termination sequence after a specified number of characters, without splitting a word. In the next example, if the user is using a hand-held device, the number of columns in the display is 40, and a new line is represented by the sequence \r\n. On a workstation, the number of available columns is 80, and a new line is a single \n character. The platform is available as the System property application.platform:

String message = "Four score and seven years ago, our fathers " + "brought forth upon this continent a new nation: " + "conceived in liberty, and dedicated to the proposition " + "that all men are created equal. "; // Define variables to hold two parameters to word wrapping int cols; String lineSeparator = ""; // Retrieve the platform property from ...

Get Jakarta Commons Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.