Counts the number of lines in the string. - CSharp System

CSharp examples for System:String Number

Description

Counts the number of lines in the string.

Demo Code


using System.Linq;
using System.Diagnostics.Contracts;
using System;//from   w  w w.j av a2  s .  c  o m

public class Main{
        /// <summary>
        /// Counts the number of lines in the string.
        /// </summary>
        /// <param name="text">The text.</param>
        /// <returns></returns>
        public static int CountLines(this string text)
        {
            if (string.IsNullOrEmpty(text))
            {
                return 0;
            }

            int count = 0;
            int start = 0;
            bool done = false;
            while (done == false)
            {
                int n = text.IndexOf(Environment.NewLine, start, StringComparison.CurrentCulture);
                if (n == -1)
                {
                    done = true;
                    if (start < text.Length)
                    {
                        count++;
                    }
                }
                else
                {
                    start = n + Environment.NewLine.Length;
                    count++;
                }
            }

            return count;
        }
}

Related Tutorials