16

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!

Greg McGuffey
  • 3,116
  • 3
  • 38
  • 58
  • possible duplicate of [Can I “multiply” a string (in C#)?](http://stackoverflow.com/q/532892/588306) – Deanna Mar 05 '14 at 08:48
  • Possible duplicate of [Is there an easy way to return a string repeated X number of times?](http://stackoverflow.com/questions/3754582/is-there-an-easy-way-to-return-a-string-repeated-x-number-of-times) – Michael Freidgeim May 30 '16 at 04:28

3 Answers3

20

A slight variation on the answer by Bala R

var s = String.Concat(Enumerable.Repeat("-.", 10));
Community
  • 1
  • 1
wageoghe
  • 27,390
  • 13
  • 88
  • 116
19
var result = String.Join("", Enumerable.Repeat("-.", 10));
Bala R
  • 107,317
  • 23
  • 199
  • 210
9
string line = new String('x', 10).Replace("x", "-.");
Emond
  • 50,210
  • 11
  • 84
  • 115