How to retrieve a StringBuilder Line Count?

Jon picture Jon · Sep 3, 2010 · Viewed 37.9k times · Source

I have a StringBuilder instance where I am doing numerous sb.AppendLine("test"); for example.

How do I work out how many lines I have?

I see the class has .Length but that tells me how many characters in all.

Any ideas?

Answer

Hans Passant picture Hans Passant · Sep 3, 2010

Sorted by efficiency:

  1. Counting your AppendLine() calls
  2. Calling IndexOf() in a loop
  3. Using Regex
  4. Using String.Split()

The last one is extraordinary expensive and generates lots of garbage, don't use.