Java Word Wrap

1. Java Word Wrap Algorithm

public static String wrap(String in,int len) {
if(in.length()<len) return in;
if(in.substring(0, len).contains("\n"))
return in.substring(0, in.indexOf("\n")).trim() + "\n\n" + wrap(in.substring(in.indexOf("\n") + 1), len);
int place=Math.max(Math.max(in.lastIndexOf(" ",len),in.lastIndexOf("\t",len)),in.lastIndexOf("-",len));
return in.substring(0,place).trim()+"\n"+wrap(in.substring(place),len);

2. 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.


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));

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s