Click here to Skip to main content
12,826,151 members (28,317 online)
Click here to Skip to main content
Alternatives (8)
Add your own
alternative version

Tagged as


34 bookmarked
Posted 9 Jan 2012

Counting Lines in a String

, 18 Jun 2012 CPOL
It seems like an obvious requirement, but the .NET framework will not count occurrences of a character in a string. It's easy to do, but which way is the quickest?


Members may post updates or alternatives to this current article in order to show different approaches or add new features.

9 Jan 2012
Can't we have something as below?int n=(s.Split(new char[]{'\n'})).Length;where n is the number of lines?
10 Jan 2012
Luc Pattyn
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...
17 Jan 2012
Jon Bellamy
Again, going with other people's comments about memory, how about using a Streamreader? (I haven't tested the timings (or code) but from memory..This should be fast (and memory efficient) least in my experience.StreamReader sr = new StreamReader("Put file here");Int32 cnt =...
9 Jan 2012
I've compared your favorite with seven alternatives:static long LinesCount(string s) { long count = 0; int position = 0; while ((position = s.IndexOf('\n', position)) != -1) { count++; position++; // Skip this occurance! } ...
11 Jan 2012
George Swan
How about using the extension method: return s.Count(c => (c == '\n'));
17 Jan 2012
Greg Baryza
I had to do something like this in XSLT. If the string is not too long (for some definition of "too long"), you can replace all newlines with "" and then take the difference in the two string lengths.
17 Jan 2012
Roman Shero
Hello! Great tip!What do you think about this extension method:public static class StringExtension{ public unsafe static long LineCount(this string s) { long lineCount = 1; fixed (char* pchar = s) { char* p = pchar; for (; *p...
28 Feb 2012
Andreas Gieriet
Great analysis!I found out that Regex can be accelerated by a factor of about two.Instead of new Regex(@"\n", RegexOptions.Compiled|RegexOptions.Multiline);you can speed up by using:new Regex(@"^.*?$", RegexOptions.Compiled|RegexOptions.Multiline);But admittedly, nothing beats...


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


About the Author

Wales Wales
Born at an early age, he grew older. At the same time, his hair grew longer, and was tied up behind his head.
Has problems spelling the word "the".
Invented the portable cat-flap.
Currently, has not died yet. Or has he?

| | Privacy | Terms of Use | Mobile
Web02 | 2.8.170326.1 | Last Updated 18 Jun 2012
Article Copyright 2012 by OriginalGriff
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid