Piotr Stapp
Piotr Stapp

Reputation: 19830

StringBuilder append same char multiple times

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.

Upvotes: 5

Views: 9077

Answers (3)

Soner Gönül
Soner Gönül

Reputation: 98750

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.

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1062855

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);

Upvotes: 21

Mehmet Ataş
Mehmet Ataş

Reputation: 11549

You can use string constructor

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

Upvotes: 5

Related Questions