Monday, June 23, 2014

StringBuilder in C# - Tricky truncating with Length and Append

StringBuilder, unlike String, is a class that allows you to change the length of a string. If the length property is already set and a new string is created that is longer than the length, the length increases. If the new string is shorter than the property value already set, it decreases. The MSDN source code provides a more technical way of putting it. (See lines 464-467.)

Here's a simple example to demonstrate:

      StringBuilder example = new StringBuilder("Hello");
      //length changes from default value of 0 to 5 on creation of the object
      Console.WriteLine(example.Length);
      //output is 5

Using the append method, I add the string "Hello" onto an empty string.

      StringBuilder example = new StringBuilder("");
      //this is an empty string; length is still 0 
      example.Append("Hello");
      Console.WriteLine(example.Length);
      //output is still 5 

Using the append method, I add the string "Hello" onto a string containing only a space character.
      StringBuilder example = new StringBuilder(" ");
      //this is NOT an empty string
      //there is a space character in this string; current length is now 1 
      Console.WriteLine(example.Length);
      //output is 1
      example.Append("Hello");
      Console.WriteLine(example.Length);
      //output is now 6, because there is a space character at the beginning of the string
      Console.WriteLine(example);//output is " Hello" - there will be a space before "H"

Just remember that an empty string ("") is not the same as (" "). The latter contains a space character. This makes a big difference if you're appending your string and then getting the length. Not that I expect this is done on a regular basis, but the moral of the story is to make sure you know what prior strings contained before appending or you might get a surprise. (Not that this ever happened to me.)

So what if I wanted to get rid of the space character? Truncate.

         StringBuilder x = new StringBuilder(" ");
         Console.WriteLine(x.Length);//output is 1 because of the space character
         x.Length = 0;
         x.Append("Hello");
         Console.WriteLine(x);//output is "Hello"; notice there is no space before "Hello" now
         Console.WriteLine(x.Length);//output is 5;

Here is a screenshot to show the code and output.



No comments:

Post a Comment