在Java中以字为单位包装多个字符后的字符串 [英] Wrap the string after a number of characters word-wise in Java

查看:86
本文介绍了在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个字符的前一个空格之后的字符串,就像它的第一行一样:

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:

一个很长的字符串

第二行将是

containing many

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

Please give some proper solution.

推荐答案

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

这篇关于在Java中以字为单位包装多个字符后的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆