Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count the number of lines in a Java String

Tags:

java

string

lines

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.

like image 707
Simon Guo Avatar asked May 17 '10 15:05

Simon Guo


People also ask

How do I count the number of lines in a string in Java?

Instantiate a String class by passing the byte array obtained, as a parameter its constructor. Now, split the above string into an array of strings using the split() method by passing the regular expression of the new line as a parameter to this method. Now, find the length of the obtained array.

How do you count lines in a string?

To count the number of lines of a string in JavaScript, we can use the string split method. const lines = str. split(/\r\n|\r|\n/);

How do I count the number of lines in a Java project?

After installation: - Right click on your project - Choose codepro tools --> compute metrics - And you will get your answer in a Metrics tab as Number of Lines. This one is actually quite good!

How do you count text in Java?

Insatiate a String class by passing the byte array to its constructor. Using split() method read the words of the String to an array. Create an integer variable, initialize it with 0, int the for loop for each element of the string array increment the count.


2 Answers

private static int countLines(String str){    String[] lines = str.split("\r\n|\r|\n");    return  lines.length; } 
like image 100
Tim Schmelter Avatar answered Sep 19 '22 00:09

Tim Schmelter


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

like image 39
Martijn Courteaux Avatar answered Sep 22 '22 00:09

Martijn Courteaux