如何在字符串的特定索引处添加换行符?

4

我有一个字符串:

String testString= "For the time being, programming is a consumer job, assembly line coding is the norm, and what little exciting stuff is being performed is not going to make it compared to the mass-marketed cräp sold by those who think they can surf on the previous half-century's worth of inventions forever"

像这样:暂时,编程……

在这个字符串中的每20个字符之后,我想要插入一个换行符\n,以在Android的TextView中显示。

4个回答

7

您必须使用正则表达式来完成您的任务,它快速高效。请尝试以下代码:

String str = "....";
String parsedStr = str.replaceAll("(.{20})", "$1\n");

(.{20})将捕获20个字符的一组。第二个中的$1将放置该组的内容。然后,\n将附加到刚刚匹配的20个字符。


天才,我正在考虑撤回我的答案^^ - Philipp Jahoda
我确实喜欢简短的代码 - 但是这个(由于正则表达式编译)比我的解决方案慢得多(6倍)。 - laune
短代码:str.replaceAll(".{20}", "$0\n") - Boann

3
像这样的东西怎么样?
String s = "...whateverstring...";  

for(int i = 0; i < s.length(); i += 20) {
    s = new StringBuffer(s).insert(i, "\n").toString();
}

1
我知道在这种情况下使用 StringBufferinsert 方法,或者使用正则表达式会有更好的技术解决方案,但是我将展示一种不同的算法方法,使用 String#substring 函数:
String s = "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789";

int offset = 0; // each time you add a new character, string has "shifted"
for (int i = 20; i + offset < s.length(); i += 20) {
    // take first part of string, add a new line, and then add second part
    s = s.substring(0, i + offset) + "\n" + s.substring(i + offset);
    offset++;
}

System.out.println(s);

结果是这样的:
12345678901234567890
12345678901234567890
12345678901234567890
12345678901234567890
12345678901234567890
1234567890123456789

-2
    StringBuilder sb = new StringBuilder();
    int done = 0;
    while( done < s.length() ){
        int todo = done + 20 < s.length() ? 20 : s.length() - done;
        sb.append( s.substring( done, done + todo ) ).append( '\n' );
        done += todo;
    }
    String result = sb.toString();

这也在末尾添加了一个换行符,但您可以轻松修改以避免这种情况。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接