這是一個測試驅動的解決方案。
import junit.framework.TestCase;
public class InsertLinebreaksTest extends TestCase {
public void testEmptyString() throws Exception {
assertEquals("", insertLinebreaks("", 5));
}
public void testShortString() throws Exception {
assertEquals("abc def", insertLinebreaks("abc def", 5));
}
public void testLongString() throws Exception {
assertEquals("abc\ndef\nghi", insertLinebreaks("abc def ghi", 1));
assertEquals("abc\ndef\nghi", insertLinebreaks("abc def ghi", 2));
assertEquals("abc\ndef\nghi", insertLinebreaks("abc def ghi", 3));
assertEquals("abc def\nghi", insertLinebreaks("abc def ghi", 4));
assertEquals("abc def\nghi", insertLinebreaks("abc def ghi", 5));
assertEquals("abc def\nghi", insertLinebreaks("abc def ghi", 6));
assertEquals("abc def\nghi", insertLinebreaks("abc def ghi", 7));
assertEquals("abc def ghi", insertLinebreaks("abc def ghi", 8));
}
public static String insertLinebreaks(String s, int charsPerLine) {
char[] chars = s.toCharArray();
int lastLinebreak = 0;
boolean wantLinebreak = false;
StringBuffer sb = new StringBuffer();
for (int i = 0; i < chars.length; i++) {
if (wantLinebreak && chars[i] == ' ') {
sb.append('\n');
lastLinebreak = i;
wantLinebreak = false;
} else {
sb.append(chars[i]);
}
if (i - lastLinebreak + 1 == charsPerLine)
wantLinebreak = true;
}
return sb.toString();
}
}