Suvonkar Suvonkar - 17 days ago 8
Java Question

Wrap the string after a number of characters word-wise in Java

I have this code:

string s = "A very long string containing " +
"many many words and characters. " +
"Newlines will be entered at spaces.";

StringBuilder sb = new StringBuilder(s);

int i = 0;
while ((i = sb.indexOf(" ", i + 20)) != -1) {
sb.replace(i, i + 1, "\n");
}

System.out.println(sb.toString());


The output of the code is:

A very long string containing
many many words and
characters. Newlines
will be entered at spaces.


The above code is wrapping the string after the next space of every 30 characters, but I need to wrap the string after the previous space of every 30 characters, like for the first line it will be:

A very long string


And the 2nd line will be

containing many


Please give some proper solution.

Answer