获取 Stringbuffer 中换行符开头的索引

发布于 2024-12-08 05:38:52 字数 390 浏览 1 评论 0原文

我需要在循环 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' 不是一个字符。有什么想法吗? :)

谢谢

I need to get the starting position of new line when looping through a StringBuffer.
Say I have the following document in a stringbuffer

"This is a test
Test
Testing Testing"

New lines exist after "test", "Test" and "Testing".

I need something like:

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

}

I know that won't work because '\n' isn't a character. Any ideas? :)

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

东走西顾 2024-12-15 05:38:52

您可以这样简化循环:

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);
}

You can simplify your loop as such:

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);
}
半仙 2024-12-15 05:38:52
System.out.println("New line at " + stringBuffer.indexOf("\n"));

(不再需要循环)

System.out.println("New line at " + stringBuffer.indexOf("\n"));

(no loop necessary anymore)

香草可樂 2024-12-15 05:38:52

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

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

Your code works fine with a couple of syntactical modifications:

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);
    }
}

Console output:

New line at 14
New line at 19
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文