5

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

Decrypter
  • 2,784
  • 12
  • 38
  • 57

3 Answers3

8

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);
}
beny23
  • 34,390
  • 5
  • 82
  • 85
2
System.out.println("New line at " + stringBuffer.indexOf("\n"));

(no loop necessary anymore)

Guillaume
  • 22,694
  • 14
  • 56
  • 70
1

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
Ioeth
  • 122
  • 1
  • 1
  • 7