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
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 System String platform = System.getProperty("application.platform"); if( platform.equals( "Handheld" ) ) { cols = 40; lineSeparator = "\r\n"; } else if( platform.equals( "Workstation" ) { cols = 80; lineSeparator = "\n"; } // Wrap the text. String wrappedString = WordUtils.wrapText( message, cols, lineSeparator, true );
Depending on the platform, the wrappedString
variable now holds the initial
paragraph of the Gettysburg Address wrapped to fit either a 40-column
handheld device or an application running on a workstation with an
80-column display.
To wrap text for presentation on the Web, use the line termination
sequence <br/>
to add an HMTL
line break. The following example wraps text with <br/>
, and introduces an option to
prevent WordUtils
from wrapping
larger words:
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. http://www.oreilly.com/Gettysburg "; // Wrap the text. String wrappedString = WordUtils.wrap( message, 40, "<br/>", false );
In this example, the Gettysburg Address is formatted to fit into
40 columns in an HTML document. The final parameter to the WordUtils.wrap( )
method tells the wrapping
algorithm not to bother wrapping large words, such as the long URL at
the end of the text. Wrapping a long word would prevent people from
being able to copy this URL correctly.