14

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
  • 2,698
  • 3
  • 30
  • 51
  • 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

19
var result = String.Join("", Enumerable.Repeat("-.", 10));
Bala R
  • 101,930
  • 22
  • 186
  • 204
19

A slight variation on the answer by Bala R

var s = String.Concat(Enumerable.Repeat("-.", 10));
Community
  • 1
  • 1
wageoghe
  • 26,334
  • 13
  • 79
  • 113
9
string line = new String('x', 10).Replace("x", "-.");
Emond Erno
  • 48,121
  • 11
  • 77
  • 106