【问题标题】:How do you add a newline character in a string at specific indices?如何在特定索引处的字符串中添加换行符?
【发布时间】:2014-07-02 08:33:20
【问题描述】:

我有一个字符串:

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"

像这样:暂时编程\n........\n.......\n

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

【问题讨论】:

    标签: java android string


    【解决方案1】:

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

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

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

    【讨论】:

    • 天才,我正在考虑撤销我的回答^^
    • 我确实喜欢短代码 - 但这(由于正则表达式编译 - 比我的解决方案慢得多(因素 6)。
    • 短:str.replaceAll(".{20}", "$0\n")
    【解决方案2】:

    这样的事情怎么样?

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

    【讨论】:

      【解决方案3】:

      我知道有一个技术上更好的解决方案可以为该类使用 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
      

      【讨论】:

        【解决方案4】:
            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();
        

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

        【讨论】:

          猜你喜欢
          • 2011-10-20
          • 2012-01-20
          • 2022-06-29
          • 1970-01-01
          • 2017-01-14
          • 1970-01-01
          • 2012-06-02
          • 2015-10-30
          相关资源
          最近更新 更多