As kdgregory suggested, using would StringBuilderprobably be a simpler way of dealing with string manipulations.
Since I was not sure that the number of characters before entering a new line is a word before or after 30 characters, I decided to go to the word after 30 characters, as the implementation is probably simpler.
, " ", 30 , StringBuilder.indexOf. , a \n StringBuilder.insert.
( , \n - , , System.getProperty("line.separator");).
:
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 + 30)) != -1) {
sb.replace(i, i + 1, "\n");
}
System.out.println(sb.toString());
:
A very long string containing many
many words and characters. Newlines
will.
, , String, . , .
while, for, .
, StringBuilder.insert StringBuilder.replace, , replace, insert.