Count the number of lines in a Java String
private static int countLines(String str){
String[] lines = str.split("\r\n|\r|\n");
return lines.length;
}
With Java-11 and above you can do the same using the String.lines()
API as follows :
String sample = "Hello\nWorld\nThis\nIs\t";
System.out.println(sample.lines().count()); // returns 4
The API doc states the following as a portion of it for the description:-
Returns: the stream of lines extracted from this string
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.
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);
).