6

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.

2
  • Can you show the code you already got? What are you trying to achieve? Why is it ineffektive? Peformance/Memory? Commented Jun 3, 2013 at 12:37
  • Because it is a simple for Commented Jun 3, 2013 at 12:43

3 Answers 3

22

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);
Sign up to request clarification or add additional context in comments.

Comments

5

You can use string constructor

sb.Append(new String('a', 3)); // equals  sb.Append("aaa")

1 Comment

I did not know StringBuilders append overload stated by Marc. It is obviously better (:
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.