Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a StringBuilder is empty?

I want to test if the StringBuilder is empty but there is no IsEmpty method or property.

How does one determine this?

like image 504
Boiethios Avatar asked Aug 01 '17 08:08

Boiethios


People also ask

How do you check if a StringBuilder is empty or not?

Check if StringBuilder Is Empty Using the Length Property The StringBuilder class has a property named Length that shows how many Char objects it holds. If Length is zero that means the instance contains no characters.

How do you do null check for StringBuilder in Java?

If a variable is null then is not referring to anything. So, if you have StringBuilder s = null , that means that s is of type StringBuilder but it is not referring to a StringBuilder instance. If you have a non- null reference then you are free to call methods on the referred object.

How do I check if a StringBuffer is null?

so you can use the fact that StringBuffer. length() returns zero (or not) to check if the buffer is empty (or not).

How do I know the size of my 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.


1 Answers

If you look at the documentation of StringBuilder it has only 4 properties. One of them is Length.

The length of a StringBuilder object is defined by its number of Char objects.

You can use the Length property:

Gets or sets the length of the current StringBuilder object.

StringBuilder sb = new StringBuilder();  if (sb.Length != 0) {     // you have found some difference } 

Another possibility would be to treat it as a string by using the String.IsNullOrEmpty method and condense the builder to a string using the ToString method. You can even grab the resulting string and assign it to a variable which you would use if you have found some differences:

string difference = "";   if (!String.IsNullOrEmpty(difference = sb.ToString())) {     Console.WriteLine(difference);       } 
like image 72
Mong Zhu Avatar answered Sep 23 '22 00:09

Mong Zhu