开发者

Get the index of the start of a newline in a Stringbuffer

开发者 https://www.devze.com 2023-04-10 20:01 出处:网络
I need to get the starting position of new line when looping through a StringBuffer. Say I have the following document in a st开发者_如何学Pythonringbuffer

I need to get the starting position of new line when looping through a StringBuffer. Say I have the following document in a st开发者_如何学Pythonringbuffer

"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


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


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

(no loop necessary anymore)


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号