Hello, all.
In our projects I've come across a need to split a string into a
number of fixed-length strings. Sadly, there was no ready-to-use
method in StringUtils, but hopefully, this submission may be valuable.
The method tries to do its best to present a readable result.
Feel free to perform any amendments to conform to commons-lang guidelines.
/**
* Splits the string into a number of fixed-length
* strings. Word-wrap is applied to avoid cutting
* in the middle of the word. In this case the
* string is shortened.
*
* @param s String to split
* @param maxLineLength maximum length of each line
*
* @return an array of lines with <code>length <= maxLineLength</code>
*/
private String[] splitLinesClean(String s, int maxLineLength) {
// TODO arg checks with newer commons-lang Validate class
List lines = new ArrayList();
int index = 0;
String[] words = StringUtils.split(s);
while (index < words.length) {
StringBuffer sb = new StringBuffer(maxLineLength);
while (sb.length() < maxLineLength && index < words.length) {
sb.append(words[index]).append(' ');
index++;
}
if (sb.length() > maxLineLength) {
// cut last space and word
sb.deleteCharAt(sb.length() - 1);
sb.delete(sb.lastIndexOf(" "), sb.length());
index--;
}
lines.add(sb.toString());
}
return (String[]) lines.toArray(new String[lines.size()]);
}
Regards,
Andrew
---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]