- String[] rawLines = str.split("\n");
- for (int i = 0; i < rawLines.length; i++) {
- StringBuilder line = new StringBuilder();
- StringBuilder word = new StringBuilder();
- boolean inWord = false;
- for (int j = 0; j < rawLines[i].length(); j++) {
- char ch = rawLines[i].charAt(j);
- if ((ch == ' ') || (ch == '\t')) {
- if (inWord == true) {
- // We have just transitioned from a word to
- // whitespace. See if we have enough space to add
- // the word to the line.
- if (word.length() + line.length() > n) {
- // This word will exceed the line length. Wrap
- // at it instead.
- result.add(line.toString());
- line = new StringBuilder();
+ while (space > -1 && space <= i) {
+ prevSpace = space;
+ space = line.indexOf(' ', space + 1);