Greg McGuffey
Greg McGuffey

Reputation: 3316

How to repeat a set of characters

I'd like to repeat a set of characters multiple times. I know how to do it with a single character:

string line = new string('x', 10);

But what I'd like would be something more like this:

string line = new string("-.", 10);

which would result in: -.-.-.-.-.-.-.-.-.-.

I know the string constructor can't do it, but is there some other way within the BCL? Other suggestions?

Thanks!

Upvotes: 16

Views: 17717

Answers (3)

wageoghe
wageoghe

Reputation: 27608

A slight variation on the answer by Bala R

var s = String.Concat(Enumerable.Repeat("-.", 10));

Upvotes: 20

Emond
Emond

Reputation: 50672

string line = new String('x', 10).Replace("x", "-.");

Upvotes: 9

Bala R
Bala R

Reputation: 108957

var result = String.Join("", Enumerable.Repeat("-.", 10));

Upvotes: 19

Related Questions