How to count lines in a string?

Method 1:

int numLines = aDiff.text.Length - aDiff.text.Replace _
                   (Environment.NewLine, string.Empty).Length;

Method 2:

int numLines = aDiff.text.Split('\n').Length;

Both will give you number of lines in text.


A variant that does not alocate new Strings or array of Strings

private static int CountLines(string str)
{
    if (str == null)
        throw new ArgumentNullException("str");
    if (str == string.Empty)
        return 0;
    int index = -1;
    int count = 0;
    while (-1 != (index = str.IndexOf(Environment.NewLine, index + 1)))
        count++;

   return count + 1;
}

Tags:

C#