﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
    static class LineCount
    {

        /// <summary>
        /// Count the number of lines in the file whose name we receive as an argument.
        /// Uses ReadLine and is fairly fast.
        /// </summary>
        /// <param name="fileName">The filename and path that we need to count lines in.</param>
        /// <returns>The number of lines in the file.</returns>
        public static long CountLinesInFile(string fileName)
        {
            long count = 0;
            using (StreamReader reader = new StreamReader(fileName))
            {
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    count++;
                }
            }
            return count;
        }

        /// <summary>
        /// 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.
        /// </summary>
        /// <param name="text">The string you want to count lines in.</param>
        /// <returns>The number of lines in the string.</returns>
        public static long CountLinesInStringSlow(string text)
        {
            Regex reg = new Regex("\n", RegexOptions.Multiline);
            MatchCollection mat = reg.Matches(text);
            return mat.Count + 1;
        }

        /// <summary>
        /// This method counts the number of lines in a string passed as the argument.
        /// It uses simple IndexOf and interation to count the newlines. I start
        /// count at 1 because there is always at least one line in the string.
        /// </summary>
        /// <param name="text">You want to count the lines in this.</param>
        /// <returns>The number of lines in the string.</returns>
        public static long CountLinesInString(string text)
        {
            long count = 1;
            int start = 0;
            while ((start = text.IndexOf('\n', start)) != -1)
            {
                count++;
                start++;
            }
            return count;
        }
    }
}
