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

Counting lines in a string

4.89/5 (9 votes)
9 Jan 2012CPOL 11.4K  
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! } ...

I've compared your favorite with seven alternatives:


C#
static long LinesCount(string s)
 {
     long count = 0;
     int position = 0;
     while ((position = s.IndexOf('\n', position)) != -1)
     {
         count++;
         position++;         // Skip this occurance!
     }
     return count;
}

static long LinesCount2(string s)
{
     long count = 0;
     int posMax = s.Length;

     for (int position = 0; position < posMax; )
         if (s[position++] == '\n')
             count++;

     return count;
}

static long LinesCount3(string s)
{
     long count = 0;
     int posMax = s.Length;
     char[] a = s.ToCharArray();

     for (int position = 0; position < posMax; )
         if (a[position++] == '\n')
             count++;

     return count;
}

static long LinesCount4(string s)
{
     long count = 0;
     int position = -1;
     while ((position = s.IndexOf('\n', position + 1)) != -1)
     {
         count++;
     }
     return count;
}

static long LinesCount5(string s)
{
     long count = 0;
     int posMax = s.Length;
     char[] a = s.ToCharArray();

     foreach (char c in a)
         if (c == '\n')
             count++;

     return count;
}

static long LinesCount6(string s)
{
     long count = 0;

     foreach (char c in s)
         if (c == '\n')
             count++;

     return count;
}

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

static long LinesCount8(string s)
{
     return s.Split('\n').Length - 1;
}

The fastest was LinesCount4() which is a slight variation of your original. I've just reduced the loop by one variable assignment. Some of the other contenders look nice. Others eat up a lot of memory. LinesCount6() is probably a good compromise between speed and style.


Greetings!

License

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