Skip to content
Advertisement

Java text wrap issue, caused by input width

I am trying to wrap text based on a width of 10 characters. After looking at other questions, I have the following:

StringBuilder sb = new StringBuilder(s);

int i = 0;
while (i + 10 < sb.length() && (i = sb.lastIndexOf(" ", i + 10)) != -1) {
    sb.replace(i, i + 1, "n");
}

System.out.println(sb.toString());

This works until a word in my string is longer than the specified width. When this occurs, the rest of the string is printed on line line instead of still following the line width rule. Any ideas? I tried an “else” with a separate condition but I couldn’t get it to work. Apologies if this seems rather trivial.

Advertisement

Answer

When you have a word that’s longer than 9 characters, sb.lastIndexOf("", i + 10) gives you -1. That’s because index of the next space is greater than i + 10 and sb.lastIndexOf("", i + 10) starts from index i + 10 and looks for a space until the beginning of the string and cannot find any spaces (they have all been replaced with new lines). You can fix your code like below to make it work.

    StringBuilder sb = new StringBuilder(s);

    int i = 0;
    while (i + 10 < sb.length() && 
            (i = Math.max( sb.indexOf(" ", i), sb.lastIndexOf(" ", i + 10))) != -1) {
        sb.replace(i, i + 1, "n");
    }

    System.out.println(sb.toString());
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement