Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve a StringBuilder Line Count?

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?

like image 507
Jon Avatar asked Sep 03 '10 13:09

Jon


People also ask

How do you count lines in a string?

We can also count the number of lines present in the given string using the IndexOf() method. This method is used to find the zero-based index of the first occurrence of the given character in the given string.

How do I find the length of a StringBuilder?

The length() method of StringBuilder class returns the number of character the StringBuilder object contains. The length of the sequence of characters currently represented by this StringBuilder object is returned by this method.

How do you get string out of StringBuilder?

You can use . ToString() to get the String from the StringBuilder .

What does StringBuilder return?

The toString() method of the StringBuilder class is the inbuilt method used to return a string representing the data contained by StringBuilder Object. A new String object is created and initialized to get the character sequence from this StringBuilder object and then String is returned by toString().


1 Answers

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.

like image 192
Hans Passant Avatar answered Sep 20 '22 15:09

Hans Passant