0

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.

2
  • so you want a newline every 10 chars unless it is a whitespace? Commented Sep 16, 2016 at 17:29
  • Yes, that's the intention Commented Sep 16, 2016 at 22:08

3 Answers 3

1

There is a ready solution for that.

https://mvnrepository.com/artifact/org.apache.commons/commons-text

WordUtils.wrap(s, 10);
Sign up to request clarification or add additional context in comments.

Comments

0

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());

2 Comments

This works except for now the very last word is on it's own line.
I think you should use i + 10 < sb.length() - 1 instead of i + 10 < sb.length(), as it divides the last line if it contains spaces and is exactly 10 characters. If i + 10 = sb.length() - 1 you should skip the check.
0

You could convert your string to an array of characters and visit them and ask if the variable iterator % 10 (in this case in 9 because i = 0), if so You enter a line break plus the character, all this will be added to a StringBuilder ... might be a solution

 char[] a="ABCDFGHIKLMNOPQRSTUVWXYZ".toCharArray(); //String convert to charArray
    StringBuilder sb =  new StringBuilder(a.length);
    for (int i = 0; i < a.length; i++) {
        if(i%9==0) sb.append("\n" + a[i]); //
        sb.append(a[i]);
    }
    System.out.println(sb.toString());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.