question

Shervan360-6172 avatar image
0 Votes"
Shervan360-6172 asked Castorix31 answered

Grow Capacity of String Bulider in C#

Hello,

While the capacity is 200 and the size of StringBuilder is just132, the StringBuilder has grown to 212. why?

  class Program
     {
         static void Main(string[] args)
         {
             StringBuilder sb = new StringBuilder("Initial String. ", 200);
             int jumpCount = 10;
             string[] animals = {"goats", "cats", "pigs"};
                
             // print some basic stats about the StringBuilder
             Console.WriteLine($"Capacity: {sb.Capacity}; Length: {sb.Length}");
    
             // Add some strings to the builder using Append
             sb.Append("The quick brown fox ");
             sb.Append("jumps over the lazy dog.");
    
             // AppendLine can append a line ending
             sb.AppendLine();
    
             // AppendFormat can be used to append formatted strings
             sb.AppendFormat("He did this {0} times.", jumpCount);
             sb.AppendLine();
    
             // AppendJoin can iterate over a set of values
             sb.Append("He also jumped over ");
             sb.AppendJoin(",", animals);
    
             // Modify the content using Replace
             sb.Replace("fox", "cat");
    
             // Insert content at any index
             sb.Insert(0, "This is the ");
    
             Console.WriteLine($"Capacity: {sb.Capacity}; Length: {sb.Length}");
                
             // Convert to a single string
             Console.WriteLine(sb.ToString());
         }
     }


Capacity: 200; Length: 16
Capacity: 212; Length: 132
This is the Initial String. The quick brown cat jumps over the lazy dog.
He did this 10 times.
He also jumped over goats,cats,pigs


dotnet-csharp
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

Castorix31 avatar image
0 Votes"
Castorix31 answered

You added 12 characters to the capacity with

 sb.Insert(0, "This is the ");

From documentation :

     // ... Existing characters are shifted to make room for the new text.
     // The capacity is adjusted as needed. If value equals String.Empty, the
     // StringBuilder is not changed.


5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.