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;
}

You can also use Linq to count occurrences of lines, like this:

int numLines = aDiff.Count(c => c.Equals('\n')) + 1;

Late, but offers alternative to other answers.


Inefficient, but still:

var newLineCount = aDiff.Text.Split('\n').Length -1;