65.9K
CodeProject is changing. Read more.
Home

Counting Lines in a String

starIconstarIconstarIconstarIconstarIcon

5.00/5 (2 votes)

Jan 10, 2012

CPOL
viewsIcon

10506

This is an alternative to "Counting Lines in a String".

You shouldn't be working with huge strings at all.
If this represents a file's content, read it using File.ReadAllLines() and take the array's Length.
Otherwise, count the lines while you collect the data, not afterwards.

Dealing with a huge string isn't doing the caches any favors.
And if you can't avoid it, I would consider:

static long LinesCount(string s) {return s.Length-s.Replace("\n","").Length;}

which was in one of my very first CP posts, a couple of years ago.

:)