I want to format a String, ready for output to a terminal window. The terminal window itself does not automatically wrap long lines, so I want to insert line breaks into the String.
Is there a way to achieve this using the String.format()
method?
EDIT: Just to clarify. I do not want to hard code the line-breaks into the String.
I want to go from an Input like this:
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
To an output like this:
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor \n incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud \n exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure \n dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.\n Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt \n mollit anim id est laborum.
(Emphasis for readability)
There's no way to insert line breaks with String.format
, but you can use a regular expression to do it. For example this splits a string into lines of 50 characters max by whitespace:
str += "\n"; // Needed to handle last line correctly
str = str.replaceAll("(.{1,50})\\s+", "$1\n");
It's not perfect though; "words" longer than the maximum wont get split for example.
I would suggest you use an existing library, such as Apache Commons Lang WordUtils.wrap() rather than writing something yourself using String.format()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With