Note: This answer is more to do with the abstract task of counting lines in a string, rather than to do with the GUI side of things. It's probably not as useful as some other answers for the original questioner, but I suspect it's useful in similar situations which don't involve GUIs. If enough people reckon it's not relevant here, I'll delete it.
I would use an existing type which already knows about line endings, namely TextReader
, in conjunction with my LineReader
type from MiscUtil:
string text = "ab\ncd";
int lines = new LineReader(() => new StringReader(text)).Count();
Alternatively, without the dependencies:
public IEnumerable<string> GetLines(string text)
{
using (TextReader reader = new StringReader(text))
{
string line;
while ((line = reader.ReadLine()) != null)
{
return line;
}
}
}
then:
int lineCount = GetLines(text).Count();
Note that this will count actual lines of text rather than line breaks - this may subtly different from what you want (e.g. it'll normally be line breaks + 1, but not if there's a line break at the end of the text).