开发者

Wrap the string after a number of characters word-wise in Java

I have this code:

    String s = "A very long string cont开发者_如何学Caining " +
                   "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.


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


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.


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)


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


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


"\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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜