Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is automatic line break with string formatter possible?

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)

like image 943
maxf130 Avatar asked Feb 16 '23 12:02

maxf130


2 Answers

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.

like image 150
Joni Avatar answered Feb 18 '23 12:02

Joni


I would suggest you use an existing library, such as Apache Commons Lang WordUtils.wrap() rather than writing something yourself using String.format().

like image 35
Duncan Jones Avatar answered Feb 18 '23 10:02

Duncan Jones