Suppose I have a string, for example,
string snip = "</li></ul>";
I want to basically write it multiple times, depending on some integer value.
string snip = "</li></ul>";
int multiplier = 2;
// TODO: magic code to do this
// snip * multiplier = "</li></ul></li></ul>";
EDIT: I know I can easily write my own function to implement this, I was just wondering if there was some weird string operator that I didn't know about
In .NET 4 you can do this:
String.Concat(Enumerable.Repeat("Hello", 4))
Note that if your "string" is only a single character, there is an overload of the string constructor to handle it:
int multipler = 10;
string TenAs = new string ('A', multipler);
Unfortunately / fortunately, the string class is sealed so you can't inherit from it and overload the * operator. You can create an extension method though:
public static string Multiply(this string source, int multiplier)
{
StringBuilder sb = new StringBuilder(multiplier * source.Length);
for (int i = 0; i < multiplier; i++)
{
sb.Append(source);
}
return sb.ToString();
}
string s = "</li></ul>".Multiply(10);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With