在Java中以字为单位包装多个字符后的字符串

时间:2010-11-18 07:51:50

标签: java

我有这段代码:

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

代码的输出是:

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

上面的代码将字符串包装在每30个字符的下一个空格之后,但是我需要将字符串包装在每30个字符的前一个空格之后,就像它的第一行一样:

A very long string

第二行将是

containing many

请给出一些正确的解决方案。

6 个答案:

答案 0 :(得分:26)

您可以使用Apache-common's WordUtils.wrap()

答案 1 :(得分:15)

使用lastIndexOf代替indexOf,例如

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

这将产生以下输出:

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

答案 2 :(得分:1)

您可以尝试以下操作:

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

调用wrapString(“asd xyz afz”,“\ n”,5)

答案 3 :(得分:0)

我知道这是一个老问题,但是。 。 。根据我在这里找到的另一个答案,但不记得海报的名字。 Kuddos向他/她指出了我正确的方向。

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

答案 4 :(得分:-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();
                    }
                }
            }
         }
     }

这可以是实现的一种方式

答案 5 :(得分:-1)

“\ n”进行自我包裹。

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

这将解决您的问题