How do I wrap words in a String at a particular width?
Author: Deron Eriksson
Description: This Java example shows how to wrap words in a String at a particular wrap length.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0)


The WordUtils utility class in the Commons LangS library has two methods for performing word wrapping given a String. The first wrap() method takes the String to wrap as its first argument and the wrap length as its second argument. The second wrap() method takes for arguments. The first is the String to wrap and the second is the wrap length. The third is the newline characters to use when a line is wrapped. The fourth argument specifies whether a long word should be wrapped or not. The WrapTest class demonstrates these methods.

WrapTest.java

package test;

import java.io.IOException;

import org.apache.commons.lang.WordUtils;

public class WrapTest {

	public static void main(String[] args) throws IOException {
		String str = "This is a sentence that we're using to test the wrap method";
		System.out.println("Original String 1:\n" + str);
		System.out.println("\nWrap length of 10:\n" + WordUtils.wrap(str, 10));
		System.out.println("\nWrap length of 20:\n" + WordUtils.wrap(str, 20));
		System.out.println("\nWrap length of 30:\n" + WordUtils.wrap(str, 30));

		String str2 = "This is a sentence that we're using to test the wrap method and hereisaveryveryveryverylongword";
		System.out.println("\nOriginal String 2:\n" + str2);
		System.out.println("\nWrap length of 10, <br/>\\n newline, wrap long words:\n"
				+ WordUtils.wrap(str2, 10, "<br/>\n", true));
		System.out.println("\nWrap length of 20, \\n newline, don't wrap long words:\n"
				+ WordUtils.wrap(str2, 20, "\n", false));
	}

}

The console output from the execution of WrapTest is shown below.

Results

Original String 1:
This is a sentence that we're using to test the wrap method

Wrap length of 10:
This is a
sentence
that we're
using to
test the
wrap
method

Wrap length of 20:
This is a sentence
that we're using to
test the wrap method

Wrap length of 30:
This is a sentence that we're
using to test the wrap method

Original String 2:
This is a sentence that we're using to test the wrap method and hereisaveryveryveryverylongword

Wrap length of 10, <br/>\n newline, wrap long words:
This is a<br/>
sentence<br/>
that we're<br/>
using to<br/>
test the<br/>
wrap<br/>
method and<br/>
hereisaver<br/>
yveryveryv<br/>
erylongwor<br/>
d

Wrap length of 20, \n newline, don't wrap long words:
This is a sentence
that we're using to
test the wrap method
and
hereisaveryveryveryverylongword