Sunday, January 25, 2009

count lines in your string

The C# Cookboook by Jay Hilyard and Stephen Teilhet offers a useful solution that works properly. It uses a regular expression for counting. The following two methods contrast my regular expression method to a string-based method.

using System;
using System.Text.RegularExpressions;

class Program
{
static void Main()
{
long a = CountLinesInString("This is an\r\nawesome website.");
Console.WriteLine(a); // 2
long b = CountLinesInStringSlow("This is an awesome\r\nwebsite.\r\nYeah.");
Console.WriteLine(b); // 3
}

///
/// This method counts the number of lines in a string passed as the argument.
/// It is benchmarked in this article, but what it does is make a new Regex and
/// then get a MatchCollection on it, and then return that Count property.
///
///

The string you want to count lines in.
/// The number of lines in the string.
static long CountLinesInStringSlow(string s)
{
Regex r = new Regex("\n", RegexOptions.Multiline);
MatchCollection mc = r.Matches(s);
return mc.Count + 1;
}

///
/// This method counts the number of lines in a string passed as the argument.
/// It uses simple IndexOf and iteration to count the newlines. I start
/// count at 1 because there is always at least one line in the string.
///
/// You want to count the lines in this.
/// The number of lines in the string.
static long CountLinesInString(string s)
{
long count = 1;
int start = 0;
while ((start = s.IndexOf('\n', start)) != -1)
{
count++;
start++;
}
return count;
}
}

No comments:

Post a Comment