Count the number of lines in a Java String

2019-01-14 10:56发布

问题:

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.

回答1:

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


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



回答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.



回答4:

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


回答5:

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



回答6:

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


回答7:

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



回答8:

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


回答9:

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



回答10:

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


回答11:

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

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

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



回答12:

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



回答13:

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


回答14:

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



回答15:

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