C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,312 questions
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
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
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.