views:

339

answers:

8

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 solution at here but it is too long, I think. Thank you.

A: 

There has been a similar question to yours here. Hope it helps.

npinti
A: 

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

aioobe
@aioobe: if it should work correctly with files then it would be `System.getProperty ("line.separator");`. But I thing it's not the case and your previous (before edit) solution was correct.
Roman
ah good point .
aioobe
A: 

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

vodkhang
This doesn't work since it only splits on the sequence of `\n\r`.
aioobe
Yeah, it doesn't work. It should be a regrex there. I recommend it as a suggestion rather than a real implementation:)
vodkhang
yeah, i think Tim's code works well.
Simon Guo
+5  A: 
private static int countLines(String str){
   String[] lines = str.split("\r\n|\r|\n");
   return  lines.length;
}
Tim Schmelter
While this is perfectly good for almost all use-cases, I just want to point out that this creates a lot of Strings, that are never beeing used - but still requires memory and gc-ing. It probably only a problem on a heavily used server, or a phone or something, but it is still something of a cludge.
KarlP
+4  A: 

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(String file) {

    String content = FileUtils.readFileToString(file);
    return content.split(System.getProperty("line.separator")).length;
}
dcp
The line is not from a file, it is just a string. But it is a nice code though
Simon Guo
+2  A: 

How about this:

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

On this way you don't need to split and no new String objects will be created (what happens by String.split(String);).

Martijn Courteaux
A: 

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

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

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

volley