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

Solution 1:

In .NET 4 you can do this:

String.Concat(Enumerable.Repeat("Hello", 4))

Solution 2:

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);

Solution 3:

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);

Solution 4:

I'm with DrJokepu on this one, but if for some reason you did want to cheat using built-in functionality then you could do something like this:

string snip = "</li></ul>";
int multiplier = 2;

string result = string.Join(snip, new string[multiplier + 1]);

Or, if you're using .NET 4:

string result = string.Concat(Enumerable.Repeat(snip, multiplier));

Personally I wouldn't bother though - a custom extension method is much nicer.

Solution 5:

Just for the sake of completeness - here is another way of doing this:

public static string Repeat(this string s, int count)
{
    var _s = new System.Text.StringBuilder().Insert(0, s, count).ToString();
    return _s;
}

I think I pulled that one from Stack Overflow some time ago, so it is not my idea.