Alternatives
Members may post updates or alternatives to this current article in order to show different
approaches or add new features.
9 Jan 2012Grasshopper.iics
Can't we have something as below?int n=(s.Split(new char[]{'\n'})).Length;where n is the number of lines?
This is an alternative to "Counting Lines in a String".
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)...at least in my experience.StreamReader sr = new StreamReader("Put file here");Int32 cnt =...
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! } ...
18 Jun 2012OriginalGriff 8 alternatives
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?
How about using the extension method: return s.Count(c => (c == '\n'));
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 2012Andreas 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...
Greg has over 40 years of experience in software and hardware development. He has managed application, operating
systems, compiler, and database development groups; run multi-product documentation teams; directed customer service organizations; project-managed multi-million dollar projects; and directed product management and marketing operations groups. His experience includes liaison responsibilities with international organizations, particularly in Japan.