views:

673

answers:

12

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

Exact duplicate of 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.

A: 

There is no such statement in C#; your best bet is probably your own MultiplyString() function.

Aric TenEyck
+17  A: 

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);
Shane Fulmer
I'd make multiplier a uint to prevent infinite loops.
Eric
Very slick. I'm definitely going to start using this.
Chris Pebble
If multiplier is negative an exception will be thrown on creating the StringBuilder and the loop wouldn't even run in any case ...
Joey
Using a StringBuilder for this is probably overkill, unless the multiplier is generally very large (as in thousands).
technophile
From my own testing, using a StringBuilder where you specify the buffer size (as here) breaks even in speed with about 3-4 concatenations.
JulianR
@JulianR Good to know, thanks!
technophile
+10  A: 

If you just need a single character you can do:

new string('\t', i)

See this post for more info.

Chris Pebble
This works for my immediate problem so I guess it's the accepted answer. In general though this wouldn't work. :)
Colin Burnett
I really think the extension method Shane Fulmer posted is a better solution. I'd mark his response as the answer IMHO.
Chris Pebble
@Chris, how do I decide then between the better answer for my specific problem that led to this question and a better, more general answer?
Colin Burnett
I think Shane Fulmer's answer is a more elegant solution to your specific problem. After you implement it just do "\t".Multiply(i). Not saying I don't appreciate the points :), just think his solution is superior.
Chris Pebble
+10  A: 

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());
Noldorin
A: 

Per mmyers:

public static string times(this string str, int count)
{
  StringBuilder sb = new StringBuilder();
  for(int i=0; i<count; i++) 
  {
    sb.Append(str);
  }
  return sb.ToString();
}
John Weldon
+1  A: 
int indent = 5;
string s = new string('\t', indent);
Larsenal
+1  A: 

One way of doing this is the following - but it's not that nice.

 String.Join(String.Empty, Enumerable.Repeat("hello", 3).ToArray())

UPDATE

Ahhhh ... I remeber ... for chars ...

 new String('x', 3)
Daniel Brückner
Identical to mine. It's not the most elegant, but at least it's simple. :)
Noldorin
Re: your update, see the accepted answer.
Noldorin
A: 

As long as it's only one character that you want to repeat, there is a String constructor that you can use:

string indentation = new String('\t', indent);
Guffa
A: 

how about with a linq aggregate...

var combined = Enumerable.Repeat("hello", 5).Aggregate("", (agg, current) => agg + current);

Scott Ivey
+6  A: 

Here's how I do it...

string value = new string(' ',5).Replace(" ","Apple");
Zachary
Nice idea... +1
Daniel Brückner
slick, I'd +1 if I could
dss539
Very creative! +1
Marc
A: 

I don't think that you can extend System.String with an operator overload, but you could make a string wrapper class to do it.

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 to do would be to have your function track and pass in the current depth and dump tabs out in a for loop based off of that.

48klocs
A: 

if u need string 3 times just do

string x = "hello";

string combined = x + x + x;

Doesn't scale very nicely does it...
Marc