Displaying a String Multiple times using * operator [duplicate]
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 开发者_StackOverflowwords, 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?
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.
The answer to this, without simply hiding the loop or some other contrived example, is no.
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.
精彩评论