21

I have this code:

    String s = "A very long string containing " +
                   "many many words and characters. " +
                   "Newlines will be entered at spaces.";

    StringBuilder sb = new StringBuilder(s);

    int i = 0;
    while ((i = sb.indexOf(" ", i + 20)) != -1) {
        sb.replace(i, i + 1, "\n");
    }

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

The output of the code is:

A very long string containing
many many words and
characters. Newlines
will be entered at spaces.

The above code is wrapping the string after the next space of every 30 characters, but I need to wrap the string after the previous space of every 30 characters, like for the first line it will be:

A very long string

And the 2nd line will be

containing many

Please give some proper solution.

demongolem
  • 9,474
  • 36
  • 90
  • 105
Suvonkar
  • 2,440
  • 12
  • 34
  • 44

6 Answers6

32

You can use Apache-common's WordUtils.wrap().

SERPRO
  • 10,015
  • 8
  • 46
  • 63
Emil
  • 13,577
  • 18
  • 69
  • 108
  • 8
    Which can be downloaded from http://commons.apache.org/proper/commons-lang/download_lang.cgi – Adam Apr 29 '14 at 09:06
20

Use lastIndexOf instead of indexOf, e.g.

StringBuilder sb = new StringBuilder(s);

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

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

This will produce the following output:

A very long string
containing many
many words and
characters.
Newlines will be
entered at spaces.
vitaut
  • 49,672
  • 25
  • 199
  • 336
  • Thanks for your reply. In this example if I provide string as "A very long string122222222222222222222222222222 containing many many words and characters. Newlines will be entered at spaces." then the out put is not wrapping after the long word("string122222222222222222222222222222 ") and unexpectedly wrapping before the long word. – Suvonkar Nov 18 '10 at 09:05
  • @Suvonkar:You can look into source of [WordUtils.wrap()](http://kickjava.com/src/org/apache/commons/lang/WordUtils.java.htm) and implement it the way you like. – Emil Nov 18 '10 at 09:46
  • short and nice, like a C programmer :) `sb.replace(i, i + 1, "\n");` -> `sb.setCharAt( i, '\n' );` is an alternative – Christian Ullenboom May 30 '21 at 19:23
2

You can try the following:

public static String wrapString(String s, String deliminator, int length) {
    String result = "";
    int lastdelimPos = 0;
    for (String token : s.split(" ", -1)) {
        if (result.length() - lastdelimPos + token.length() > length) {
            result = result + deliminator + token;
            lastdelimPos = result.length() + 1;
        }
        else {
            result += (result.isEmpty() ? "" : " ") + token;
        }
    }
    return result;
}

call as wrapString("asd xyz afz","\n",5)

Yalovali
  • 31
  • 1
0

I know it's an old question, but . . . Based on another answer I found here, but can't remember the posters name. Kuddos to him/her for pointing me in the right direction.

    public String truncate(final String content, final int lastIndex) {
        String result = "";
        String retResult = "";
        //Check for empty so we don't throw null pointer exception
        if (!TextUtils.isEmpty(content)) {
            result = content.substring(0, lastIndex);
            if (content.charAt(lastIndex) != ' ') {
                //Try the split, but catch OutOfBounds in case string is an
                //uninterrupted string with no spaces
                try {
                    result = result.substring(0, result.lastIndexOf(" "));
                } catch (StringIndexOutOfBoundsException e) {
                    //if no spaces, force a break
                    result = content.substring(0, lastIndex);
                }
                //See if we need to repeat the process again
                if (content.length() - result.length() > lastIndex) {
                    retResult = truncate(content.substring(result.length(), content.length()), lastIndex);
                } else {
                    return result.concat("\n").concat(content.substring(result.length(), content.length()));
                }
            }
            //Return the result concatenating a newline character on the end
            return result.concat("\n").concat(retResult);;
            //May need to use this depending on your app
            //return result.concat("\r\n").concat(retResult);;
        } else {
            return content;
        }
    }
Aaron Bar
  • 611
  • 1
  • 7
  • 20
-1
public static void main(String args[]) {

         String s1="This is my world. This has to be broken.";
         StringBuffer buffer=new StringBuffer();

         int length=s1.length();
         int thrshld=5; //this valueis threshold , which you can use 
         int a=length/thrshld;

         if (a<=1) {
             System.out.println(s1);
         }else{
            String split[]=s1.split(" ");
            for (int j = 0; j < split.length; j++) {
                buffer.append(split[j]+" "); 

                if (buffer.length()>=thrshld) { 

                    int lastindex=buffer.lastIndexOf(" ");

                    if (lastindex<buffer.length()) { 

                        buffer.subSequence(lastindex, buffer.length()-1);
                        System.out.println(buffer.toString()); 
                        buffer=null;
                        buffer=new StringBuffer();
                    }
                }
            }
         }
     }

this can be one way to achieve

Sainath Patwary karnate
  • 3,165
  • 1
  • 16
  • 18
-3

"\n" makes a wordwrap.

String s = "A very long string containing \n" +  
"many many words and characters. \n" +
"Newlines will be entered at spaces.";

this will solve your problem

demongolem
  • 9,474
  • 36
  • 90
  • 105
TimWalter
  • 47
  • 1
  • 12