Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to count new lines in a very big string?

Tags:

string

php

count

The problem reduces to counting \n characters, so is there a function that can do it on a huge strings, since explode() wastes too much memory.

like image 466
rsk82 Avatar asked Jun 01 '11 16:06

rsk82


People also ask

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

split("\r\n|\r|\n", -1); if you look at the docs here:docs.oracle.com/javase/7/docs/api/java/lang/… it has more information. since java 1.1 there is a LineNumberReader. see my answer below.

How do you count a new line in Python?

Use readlines() to get Line Count This is the most straightforward way to count the number of lines in a text file in Python. The readlines() method reads all lines from a file and stores it in a list. Next, use the len() function to find the length of the list which is nothing but total lines present in a file.

How do you count the number of lines in a paragraph 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.


1 Answers

substr_count should do the trick:

substr_count( $your_string, "\n" ); 
like image 101
George Cummins Avatar answered Sep 29 '22 06:09

George Cummins