JAVA - Inserting a new line at the next space after 30 characters
java, newline, string
Solution
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.
Problem
I have a large block of text (200+ characters in a String) and need to insert new lines at the next space after 30 characters, to preserve words. Here is what I have now (NOT working): ``` String rawInfo = front.getItemInfo(name); String info = ""; int begin = 0; for(int l=30;(l+30)<rawInfo.length();l+=30) { while(rawInfo.charAt(l)!=' ') l++; info += rawInfo.substring(begin, l) + "\n"; begin = l+1; if((l+30)>=(rawInfo.length())) info += rawInfo.substring(begin, rawInfo.length()); } ``` Thanks for any help