Count the number of lines in a Java String

Solution 1:

private static int countLines(String str){
   String[] lines = str.split("\r\n|\r|\n");
   return  lines.length;
}

Solution 2:

How about this:

String yourInput = "...";
Matcher m = Pattern.compile("\r\n|\r|\n").matcher(yourInput);
int lines = 1;
while (m.find())
{
    lines ++;
}

This way you don't need to split the String into a lot of new String objects, which will be cleaned up by the garbage collector later. (This happens when using String.split(String);).

Solution 3:

A very simple solution, which does not create String objects, arrays or other (complex) objects, is to use the following:

public static int countLines(String str) {
    if(str == null || str.isEmpty())
    {
        return 0;
    }
    int lines = 1;
    int pos = 0;
    while ((pos = str.indexOf("\n", pos) + 1) != 0) {
        lines++;
    }
    return lines;
}

Note, that if you use other EOL terminators you need to modify this example a little.