Count the number of lines in a Java String

JavaStringLines

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

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 - Java

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

Solution 4 - Java

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.

Solution 5 - Java

I am using:

public static int countLines(String input) throws IOException {
    LineNumberReader lineNumberReader = new LineNumberReader(new StringReader(input));
    lineNumberReader.skip(Long.MAX_VALUE);
    return lineNumberReader.getLineNumber();
}

LineNumberReader is in the java.io package: https://docs.oracle.com/javase/7/docs/api/java/io/LineNumberReader.html

Solution 6 - Java

If you have the lines from the file already in a string, you could do this:

int len = txt.split(System.getProperty("line.separator")).length;

EDIT:

Just in case you ever need to read the contents from a file (I know you said you didn't, but this is for future reference), I recommend using Apache Commons to read the file contents into a string. It's a great library and has many other useful methods. Here's a simple example:

import org.apache.commons.io.FileUtils;

int getNumLinesInFile(File file) {

    String content = FileUtils.readFileToString(file);
    return content.split(System.getProperty("line.separator")).length;
}

Solution 7 - Java

If you use Java 8 then:

long lines = stringWithNewlines.chars().filter(x -> x == '\n').count() + 1;

(+1 in the end is to count last line if string is trimmed)

One line solution

Solution 8 - Java

This is a quicker version:

public static int countLines(String str)
{
	if (str == null || str.length() == 0)
		return 0;
	int lines = 1;
	int len = str.length();
	for( int pos = 0; pos < len; pos++) {
	    char c = str.charAt(pos);
	    if( c == '\r' ) {
	        lines++;
	        if ( pos+1 < len && str.charAt(pos+1) == '\n' )
	        	pos++;
	    } else if( c == '\n' ) {
	        lines++;
	    }
	}
	return lines;
}

Solution 9 - Java

Try this one:

public int countLineEndings(String str){
	
    str = str.replace("\r\n", "\n"); // convert windows line endings to linux format 
    str = str.replace("\r", "\n"); // convert (remaining) mac line endings to linux format
	
    return str.length() - str.replace("\n", "").length(); // count total line endings
}

number of lines = countLineEndings(str) + 1

Greetings :)

Solution 10 - Java

//import java.util.regex.Matcher;
//import java.util.regex.Pattern;

private static Pattern newlinePattern = Pattern.compile("\r\n|\r|\n");

public static int lineCount(String input) {
	Matcher m = newlinePattern.matcher(input);
	int count = 0;
	int matcherEnd = -1;
	while (m.find()) {
		matcherEnd = m.end();
		count++;
	}
	if (matcherEnd < input.length()) {
		count++;
	}
	
	return count;
}

This will count the last line if it doesn't end in cr/lf cr lf

Solution 11 - Java

"Hello\nWorld\nthis\nIs\t".split("[\n\r]").length

You could also do

"Hello\nWorld\nthis\nis".split(System.getProperty("line.separator")).length

to use the systems default line separator character(s).

Solution 12 - Java

Well, this is a solution using no "magic" regexes, or other complex sdk features.

Obviously, the regex matcher is probably better to use in real life, as its quicker to write. (And it is probably bug free too...)

On the other hand, You should be able to understand whats going on here...

If you want to handle the case \r\n as a single new-line (msdos-convention) you have to add your own code. Hint, you need another variable that keeps track of the previous character matched...

int lines= 1;

for( int pos = 0; pos < yourInput.length(); pos++){
    char c = yourInput.charAt(pos);
    if( c == "\r" || c== "\n" ) {
        lines++;
    }
}

Solution 13 - Java

new StringTokenizer(str, "\r\n").countTokens();

Note that this will not count empty lines (\n\n).

CRLF (\r\n) counts as single line break.

Solution 14 - Java

This method will allocate an array of chars, it should be used instead of iterating over string.length() as length() uses number of Unicode characters rather than chars.

int countChars(String str, char chr) {
	char[] charArray = str.toCharArray();
	int count = 0;
	for(char cur : charArray)
		if(cur==chr) count++;
	return count;
}

Solution 15 - Java

What about StringUtils.countMatches().

In your case

StringUtils.countMatches("Hello\nWorld\nThis\nIs\t", "\n") + StringUtils.countMatches("Hello\nWorld\nThis\nIs\t", "\r") + 1

should work fine.

Solution 16 - Java

I suggest you look for something like this

String s; 
s.split("\n\r");

Look for the instructions here for Java's String Split method

If you have any problem, post your code

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSimon GuoView Question on Stackoverflow
Solution 1 - JavaTim SchmelterView Answer on Stackoverflow
Solution 2 - JavaMartijn CourteauxView Answer on Stackoverflow
Solution 3 - JavaNamanView Answer on Stackoverflow
Solution 4 - JavaVegerView Answer on Stackoverflow
Solution 5 - JavadermoritzView Answer on Stackoverflow
Solution 6 - JavadcpView Answer on Stackoverflow
Solution 7 - JavaGleb SView Answer on Stackoverflow
Solution 8 - JavaSaxintoshView Answer on Stackoverflow
Solution 9 - JavaJavanautView Answer on Stackoverflow
Solution 10 - Javauser939857View Answer on Stackoverflow
Solution 11 - JavaaioobeView Answer on Stackoverflow
Solution 12 - JavaKarlPView Answer on Stackoverflow
Solution 13 - JavavolleyView Answer on Stackoverflow
Solution 14 - JavaGhandhikusView Answer on Stackoverflow
Solution 15 - JavaKrzysztof JanowskiView Answer on Stackoverflow
Solution 16 - JavavodkhangView Answer on Stackoverflow