Is there a fast way to append a StringBuilder multiple times in C#? Of course I can write my own extension to append in loop, but it looks ineffective.
3 Answers
There is already an Append overload that accepts char value and int repeatCount:
char c = ...
int count = ...
builder.Append(c, count);
or more simply (in many cases):
builder.Append(' ', 20);
Comments
You can use string constructor
sb.Append(new String('a', 3)); // equals sb.Append("aaa")
1 Comment
Mehmet Ataş
I did not know StringBuilders append overload stated by Marc. It is obviously better (:
StringBuilder has a constructor lile StringBuilder.Append Method (Char, Int32)
Appends a specified number of copies of the string representation of a Unicode character to this instance.
Like StringBuilder.Append(char value, int repeatCount)
For example;
StringBuilder sb = new StringBuilder();
sb.Append('*', 10);
Console.WriteLine(sb);
Output will be;
**********
Here is a DEMO.
for