Get the index of the start of a newline in a Stringbuffer
Asked Answered
F

3

6

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

Fiftyfifty answered 4/10, 2011 at 14:23 Comment(2)
'\n' is a character.Champaign
It doesn't work because capacity() is not the same as length(). Please read documentation!Senarmontite
S
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);
}
Stylographic answered 4/10, 2011 at 14:35 Comment(0)
R
2
System.out.println("New line at " + stringBuffer.indexOf("\n"));

(no loop necessary anymore)

Rooftree answered 4/10, 2011 at 14:28 Comment(4)
That will just print the index of the first '\n'. What about the others?Champaign
Thats what I need. For the others I could have a while loop and it will end when the indexOf is -1 :)Fiftyfifty
@Decrypter, you should have the for loop from beny23, as thats a nice idea.Jailhouse
Done something similar with a while loop.Fiftyfifty
A
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
Ambo answered 4/10, 2011 at 14:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.