As suggested by kdgregory, using a StringBuilder
would probably be an easier way to work with string manipulation.
Since I wasn't quite sure if the number of characters before the newline is inserted is the word before or after 30 characters, I opted to go for the word after 30 characters, as the implementation is probably easier.
The approach is to find the instance of the " "
which occurs at least 30 characters after the current character which is being viewed by using StringBuilder.indexOf
. When a space occurs, a \n
is inserted by StringBuilder.insert
.
(We'll assume that a newline is \n
here -- the actual line separator used in the current environment can be retrieved by System.getProperty("line.separator");
).
Here's the example:
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());
Result:
A very long string containing many
many words and characters. Newlines
will.
I should add that the code above hasn't been tested out, except for the example String
that I've shown in the code. It wouldn't be too surprising if it didn't work under certain circumstances.
Edit
The loop in the sample code has been replaced by a while
loop rather than a for
loop which wasn't very appropriate in this example.
Also, the StringBuilder.insert
method was replaced by the StringBuilder.replace
method, as Kevin Stich mentioned in the comments that the replace
method was used rather than the insert
to get the desired behavior.