Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Counting Lines in a String

5.00/5 (2 votes)
10 Jan 2012CPOL 10.4K  
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:

C#
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.

:)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)