Count the number of lines in a Java String

Posted by Simon Guo on Stack Overflow See other posts from Stack Overflow or by Simon Guo
Published on 2010-05-17T15:08:47Z Indexed on 2010/05/17 15:40 UTC
Read the original article Hit count: 268

Filed under:
|

Need some compact code for counting the number of lines in a string in Java. The string is to be separated by \r or \n. Each instance of those newline characters will be considered as a separate line. For example,

"Hello\nWorld\nThis\nIs\t"

should return 4. The prototype is

private static int countLines(String str) {...}

Can someone provide a compact set of statements? I have solution at here but it is too long, I think. Thank you.

© Stack Overflow or respective owner

Related posts about java

Related posts about homework