Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiplying strings in C# [duplicate]

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.

like image 747
Colin Burnett Avatar asked Jun 05 '09 20:06

Colin Burnett


4 Answers

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);
like image 97
Shane Fulmer Avatar answered Nov 12 '22 04:11

Shane Fulmer


If you just need a single character you can do:

new string('\t', i)

See this post for more info.

like image 28
Chris Van Opstal Avatar answered Nov 12 '22 03:11

Chris Van Opstal


Here's how I do it...

string value = new string(' ',5).Replace(" ","Apple");
like image 31
Zachary Avatar answered Nov 12 '22 03:11

Zachary


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());
like image 40
Noldorin Avatar answered Nov 12 '22 02:11

Noldorin