Possible Duplicate:
Can I "multiply" a string (in C#)?
In Python I can do this:
>>> i = 3
>>> 'hello' * i
'hellohellohello'
How can I multiply strings in C# similarly to in Python? I could easily do it in a for loop but that gets tedious and non-expressive.
Ultimately I'm writing out to console recursively with an indented level being incremented with each call.
parent
child
child
child
grandchild
And it'd be easiest to just do "\t" * indent
.
There is an extension method for it in this post.
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 just need a single character you can do:
new string('\t', i)
See this post for more info.
Here's how I do it...
string value = new string(' ',5).Replace(" ","Apple");
There's nothing built-in to the BCL to do this, but a bit of LINQ can accomplish the task easily enough:
var multiplied = string.Join("", Enumerable.Repeat("hello", 5).ToArray());
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