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

时间:2014-07-02 08:33:20

标签: java android string

我有一个字符串:

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"

像这样:目前,programmi \ n ........ \ n ....... \ n

在此字符串中每个长度为20个字符之后,我想在Android中的TextView中放置换行符\ n以显示。

4 个答案:

答案 0 :(得分:6)

您必须使用正则表达式才能快速高效地完成任务。请尝试以下代码: -

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

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

答案 1 :(得分:3)

这样的事情怎么样?

String s = "...whateverstring...";  

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

答案 2 :(得分:1)

我知道有一个技术上更好的解决方案,可以为该类使用StringBufferinsert方法,甚至是regex,但我会使用{{向您展示一种不同的算法方法3}}:

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

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

这也会在最后添加换行符,但您可以轻松修改它以避免这种情况。