StringBuilder.Append() pequliarities

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hello

Provided the following code:
string temp = "Short string"; // 12 chars
StringBuilder sb = new StringBuilder();
sb.Append(temp, 0, 30);

How many characters is the string in sb? 12 or is it filled with blanks to
reach 30 chars?

Greetings,
Todorov
 
Todorov,
Have you tried it?

I receive an ArgumentOutOfRangeException, as you are attempting to append
more characters then there are in the string.

Hope this helps
Jay
 
What are you actually attempting to accomplish? Do you want it padded to 30
characters? If so, you have to pad the string first:

string temp = "Short string";
StringBuilder sb = new StringBuilder();
sb.Append(temp.PadRight(30,' '));

As an often-overlooked fine point, StringBuilder has a default capacity of
16 characters and will have to reallocate memory right off to take a string
longer than that; if I remember correctly the practice is to double the
capacity for each reallocation, so the above code would expand the capacity
to 32. So ... it would be more efficient to use the constructor overload to
set the capacity to a larger size in the first place. In fact all the above
could be reduced to:

StringBuilder sb = new StringBuilder("Short string".PadRight(30,' '),30);

But you're likely going to append more stuff later and would want to
allocate an even larger buffer -- perhaps one that is on the high side of
the average expected size, or even the maximum expected size.

--Bob
 
Back
Top