String Multiplication in C #
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 in Python? I could easily do this in a for loop, but it is tedious and not expressive.
Ultimately, I write to let the console recursively, with the indentation level increasing with every call.
parent child child child grandchild And it would be easiest to do "\t" * indent .
It has an extension method 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); I do not think you can extend System.String with operator overloading, but you can make a string wrapper class to do this.
public class StringWrapper { public string Value { get; set; } public StringWrapper() { this.Value = string.Empty; } public StringWrapper(string value) { this.Value = value; } public static StringWrapper operator *(StringWrapper wrapper, int timesToRepeat) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < timesToRepeat; i++) { builder.Append(wrapper.Value); } return new StringWrapper(builder.ToString()); } } Then call it like ...
var helloTimesThree = new StringWrapper("hello") * 3; And get the value from ...
helloTimesThree.Value; Of course, the sane thing should be for your function to track and skip the current depths and dumps in a for loop based on this.