Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 943
Decrypter Avatar asked Oct 04 '11 14:10

Decrypter


2 Answers

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);
}
like image 169
beny23 Avatar answered Oct 13 '22 21:10

beny23


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

(no loop necessary anymore)

like image 37
Guillaume Avatar answered Oct 13 '22 20:10

Guillaume