Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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);).

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.

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;
}

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

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

With JDK/11 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

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;
}

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 :)

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

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++;
    }
}
new StringTokenizer(str, "\r\n").countTokens();

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

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

"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).

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;
}

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top