Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Suppose I have a string, for example,

string snip =  "</li></ul>";

I want to basically write it multiple times, depending on some integer value.

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

// TODO: magic code to do this 
// snip * multiplier = "</li></ul></li></ul>";

EDIT: I know I can easily write my own function to implement this, I was just wondering if there was some weird string operator that I didn't know about

like image 535
Ian G Avatar asked Feb 10 '09 15:02

Ian G


3 Answers

In .NET 4 you can do this:

String.Concat(Enumerable.Repeat("Hello", 4))
like image 67
Will Dean Avatar answered Oct 18 '22 13:10

Will Dean


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);
like image 124
James Curran Avatar answered Oct 18 '22 15:10

James Curran


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);
like image 62
Tamas Czinege Avatar answered Oct 18 '22 15:10

Tamas Czinege