Count the number of lines in a Java String

Simon Guo picture Simon Guo · May 17, 2010 · Viewed 82.8k times · Source

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 a solution at here but it is too long, I think. Thank you.

Answer

Tim Schmelter picture Tim Schmelter · May 17, 2010
private static int countLines(String str){
   String[] lines = str.split("\r\n|\r|\n");
   return  lines.length;
}