Splitting a string on to several different lines in Java

I have a very long string consisting of words punctuation and spaces. I am trying to modify the string to add a new line (\n) after every x characters but while preserving whole words. For example:

An evil human sprayed innocent students in the face with pepper spray

With x = 20 would output like this:

An evil human sprayed      21 chars
innocent students in       20 chars
the face with pepper       20 chars
spray                      end of string

If words would be split by inserting a \n after x characters, then the word should be allowed to stay on the line, while a new line would be inserted at the end of the word.

Is there a catch-all way of doing this without a whole lot of complicated code?


I would write:

s = s.replaceAll("(.{20,}?)\\s+", "$1\n");

This will find every instance of at least twenty non-newline characters, followed by one or more whitespace characters, and replace the whitespace with a newline. Or, to make x decidable at run-time (rather than hard-coded as 20), I'd write:

s = s.replaceAll("(.{" + x + ",}?)\\s+", "$1\n");

Take a look at the Apache commons lang library, in particular WordUtils#wrap().

Need Your Help

Pass Value/Variable to Dtsx /SET \Package.Variables;“value” ERROR

batch-file ssis flat-file

I want pass a value to ssis package, but i have an error back

Prompt user to replace certain parts of text in a string

javascript regex actionscript-3 air

I have a program that allows a user to type JavaScript in a textbox, and it executes in an HTML viewer or iframe. There is a drop down with options such as "Insert Image", which inserts