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.

6 Answers 6

32

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

Sign up to request clarification or add additional context in comments.

1 Comment

21

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.

3 Comments

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:You can look into source of WordUtils.wrap() and implement it the way you like.
short and nice, like a C programmer :) sb.replace(i, i + 1, "\n"); -> sb.setCharAt( i, '\n' ); is an alternative
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)

Comments

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;
        }
    }

Comments

-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

Comments

-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

1 Comment

Why didn't I think of that earlier??

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.