【问题标题】:Get the index of the start of a newline in a Stringbuffer获取 Stringbuffer 中换行符开始的索引
【发布时间】:2011-11-30 18:06:49
【问题描述】:

我需要在遍历 StringBuffer 时获取新行的起始位置。 假设我在字符串缓冲区中有以下文档

"This is a test
Test
Testing Testing"

在“test”、“Test”和“Testing”之后存在新行。

我需要类似的东西:

for(int i =0;i < StringBuffer.capacity(); i++){
if(StringBuffer.chatAt(i) == '\n')
    System.out.println("New line at " + i);

}

我知道这行不通,因为 '\n' 不是字符。有任何想法吗? :)

谢谢

【问题讨论】:

  • '\n' 是一个字符。
  • 它不起作用,因为容量()与长度()不同。请阅读文档!

标签: java stringbuffer


【解决方案1】:

您可以这样简化循环:

StringBuffer str = new StringBuffer("This is a\ntest, this\n\nis a test\n");

for (int pos = str.indexOf("\n"); pos != -1; pos = str.indexOf("\n", pos + 1)) {
  System.out.println("\\n at " + pos);
}

【讨论】:

    【解决方案2】:
    System.out.println("New line at " + stringBuffer.indexOf("\n"));
    

    (不再需要循环)

    【讨论】:

    • 这只会打印第一个 '\n' 的索引。其他人呢?
    • 这就是我需要的。对于其他人,我可以有一个 while 循环,它会在 indexOf 为 -1 时结束 :)
    • @Decrypter,你应该有 beny23 的 for 循环,这是个好主意。
    • 用 while 循环做类似的事情。
    【解决方案3】:

    您的代码通过几个语法修改可以正常工作:

    public static void main(String[] args) {
        final StringBuffer sb = new StringBuffer("This is a test\nTest\nTesting Testing");
    
        for (int i = 0; i < sb.length(); i++) {
            if (sb.charAt(i) == '\n')
                System.out.println("New line at " + i);
        }
    }
    

    控制台输出:

    New line at 14
    New line at 19
    

    【讨论】:

      猜你喜欢
      • 2012-11-04
      • 1970-01-01
      • 2015-05-13
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-17
      相关资源
      最近更新 更多