我有一大块文本(字符串中有200多个字符),需要在30个字符后的下一个空格处插入新行,以保留单词。这是我现在拥有的(不工作):

String rawInfo = front.getItemInfo(name);
String info = "";
int begin = 0;
for(int l=30;(l+30)<rawInfo.length();l+=30) {
    while(rawInfo.charAt(l)!=' ')
        l++;
    info += rawInfo.substring(begin, l) + "\n";
    begin = l+1;
    if((l+30)>=(rawInfo.length()))
        info += rawInfo.substring(begin, rawInfo.length());
}

感谢您的帮助

有帮助吗?

解决方案

根据kdgregory的建议,使用 StringBuilder 可能是一种更简单的字符串操作方式。

由于我不太确定插入换行符之前的字符数是30个字符之前还是之后的字,我选择了30个字符后的单词,因为实现可能更容易。

方法是找到的实例。使用 .html #indexOf(java.lang.String,%20int)“rel =”noreferrer“> StringBuilder.indexOf 。当出现空格时, \ n (int,%20char)“rel =”noreferrer“> StringBuilder.insert

(我们假设换行符是 \ n - 当前环境中使用的实际行分隔符可以通过 System.getProperty(&quot; line.separator&quot; );

以下是示例:

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 + 30)) != -1) {
    sb.replace(i, i + 1, "\n");
}

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

结果:

A very long string containing many
many words and characters. Newlines
will.

我应该补充一点,除了我在代码中显示的示例 String 之外,上面的代码还没有测试过。如果它在某些情况下不起作用就不会太令人惊讶。

修改

示例代码中的循环已被 while 循环替换,而不是循环的,这在此示例中不太合适。

此外, StringBuilder.insert 方法被 StringBuilder.replace 方法,正如Kevin Stich在评论中提到的那样使用 replace 方法而不是 insert 来获得所需的行为。

其他提示

这是一个以测试为导向的解决方案。

import junit.framework.TestCase;

public class InsertLinebreaksTest extends TestCase {
    public void testEmptyString() throws Exception {
        assertEquals("", insertLinebreaks("", 5));
    }

    public void testShortString() throws Exception {
        assertEquals("abc def", insertLinebreaks("abc def", 5));
    }

    public void testLongString() throws Exception {
        assertEquals("abc\ndef\nghi", insertLinebreaks("abc def ghi", 1));
        assertEquals("abc\ndef\nghi", insertLinebreaks("abc def ghi", 2));
        assertEquals("abc\ndef\nghi", insertLinebreaks("abc def ghi", 3));
        assertEquals("abc def\nghi", insertLinebreaks("abc def ghi", 4));
        assertEquals("abc def\nghi", insertLinebreaks("abc def ghi", 5));
        assertEquals("abc def\nghi", insertLinebreaks("abc def ghi", 6));
        assertEquals("abc def\nghi", insertLinebreaks("abc def ghi", 7));
        assertEquals("abc def ghi", insertLinebreaks("abc def ghi", 8));
    }

    public static String insertLinebreaks(String s, int charsPerLine) {
        char[] chars = s.toCharArray();
        int lastLinebreak = 0;
        boolean wantLinebreak = false;
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < chars.length; i++) {
            if (wantLinebreak && chars[i] == ' ') {
                sb.append('\n');
                lastLinebreak = i;
                wantLinebreak = false;
            } else {
                sb.append(chars[i]);
            }
            if (i - lastLinebreak + 1 == charsPerLine)
                wantLinebreak = true;
        }
        return sb.toString();
    }
}

更好的解决方案:将字符串复制到StringBuilder中,这样您就可以插入/更改字符而不会产生大量子字符串。然后使用indexOf()方法,该方法采用起始位置来查找要更改的索引。

编辑:teh codez:

public static String breakString(String str, int size)
{
    StringBuilder work = new StringBuilder(str);
    int pos = 0;
    while ((pos = work.indexOf(" ", pos + size)) >= 0)
    {
        work.setCharAt(pos, '\n');
    }
    return work.toString();
}

我会迭代字符串而不是30。你必须跟踪30。

psuedocode因为这听起来像家庭作业:

charInLine=0
iterateOver each char in rawString
    if(charInLine++ > 30 && currChar==' ')
        charInLine=0
        currChar='\n'

也许我错过了什么。什么错了

String s = ... s = s.substring(0,30)+ s.substring(30).replace('','\ n');

这将在字符30之后从换行符替换所有空格。

它的效率略低,但对于200个字符来说它确实无关紧要(对于数据操作来说这个数字非常小)。

布鲁斯

    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 + 30)) != -1) {
    sb.replace(i, i + 1, "\n");
}
System.out.println(sb.toString());

这是正确的,我也试过了。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top