0

Possible Duplicate:
Can I “multiply” a string (in C#)?

Is there a simple way to display a String multiple times by using something like str * 2?

In other words, is there a way to have:

int numTimes = 500;
String str = "\n";
String body = ""
for (int i = 0; i < numTimes; i++)
{
    body = "Hello" + str;
}

Without needing the for loop?

Community
  • 1
  • 1
Cody
  • 8,686
  • 18
  • 71
  • 126

3 Answers3

1

The answer to this, without simply hiding the loop or some other contrived example, is no.

Grant Thomas
  • 44,454
  • 10
  • 85
  • 129
1

Nope. There is no such operator.

you could do

body = "Hello" + String.Join("", Enumerable.Range(0, numTimes).Select(i => str));

but that's internally still looping.

Bala R
  • 107,317
  • 23
  • 199
  • 210
  • @Gabe to return the variable `str`. – Bala R Sep 12 '11 at 20:40
  • I see, it looks like I misread your post. I was expecting to see `Enumerable.Repeat` so I didn't understand why there was a `Select`. Obviously since you're using `Enumerable.Range` instead then you do need the `Select`. – Gabe Sep 12 '11 at 20:48
  • @Gabe I so rarely use `Enumerable.Repeat()` I forget about it's existence. This would be one case where it would be very appropriate. – Bala R Sep 12 '11 at 20:51
  • I suppose I should add that `String.Concat(...)` is somewhat more concise than `String.Join("", ...) – Gabe Sep 13 '11 at 08:14
0

Yes and no. No, not out of the box. Yes, you can make an extension method to do that pretty easily. See thread on string extension methods here C# String Operator Overloading

It would still be looping, so you should use StringBuilder, not pure concatenation, if possible, especially if you don't know how many times it will loop. Strings are immutable, so 500 loops is an awful lot of temp strings in memory.

Community
  • 1
  • 1
Nikki9696
  • 6,260
  • 1
  • 28
  • 23