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.
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.
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/);
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!
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.
private static int countLines(String str){ String[] lines = str.split("\r\n|\r|\n"); return lines.length; }
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);
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With