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
As suggested by kdgregory, using a
StringBuilderwould 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 usingStringBuilder.indexOf. When a space occurs, a\nis inserted byStringBuilder.insert.(We’ll assume that a newline is
\nhere — the actual line separator used in the current environment can be retrieved bySystem.getProperty("line.separator");).Here’s the example:
Result:
I should add that the code above hasn’t been tested out, except for the example
Stringthat 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
whileloop rather than aforloop which wasn’t very appropriate in this example.Also, the
StringBuilder.insertmethod was replaced by theStringBuilder.replacemethod, as Kevin Stich mentioned in the comments that thereplacemethod was used rather than theinsertto get the desired behavior.