Ian G
Ian G

Reputation: 30234

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

Upvotes: 158

Views: 117415

Answers (13)

user734119
user734119

Reputation: 113

This is a lot more concise:

new StringBuilder().Insert(0, "</li></ul>", count).ToString()

The namespace using System.Text; should be imported in this case.

Upvotes: 9

digEmAll
digEmAll

Reputation: 57210

A little late (and just for fun), if you really want to use the * operator for this work, you can do this :

public class StringWrap
{
    private string value;
    public StringWrap(string v)
    {
        this.value = v;
    }
    public static string operator *(StringWrap s, int n)
    {
        return s.value.Multiply(n); // DrJokepu extension
    }
}

And so:

var newStr = new StringWrap("TO_REPEAT") * 5;

Note that, as long as you are able to find a reasonable behavior for them, you can also handle other operators through StringWrap class, like \ , ^ , % etc...

P.S.:

Multiply() extension credits to @DrJokepu all rights reserved ;-)

Upvotes: 9

LukeH
LukeH

Reputation: 269338

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.

Upvotes: 13

James Curran
James Curran

Reputation: 103495

Since everyone is adding their own .NET4/Linq examples, I might as well add my own. (Basically, it DrJokepu's, reduced to a one-liner)

public static string Multiply(this string source, int multiplier) 
{ 
    return Enumerable.Range(1,multiplier)
             .Aggregate(new StringBuilder(multiplier*source.Length), 
                   (sb, n)=>sb.Append(source))
             .ToString();
}

Upvotes: 2

Frank Schwieterman
Frank Schwieterman

Reputation: 24480

If you have .Net 3.5 but not 4.0, you can use System.Linq's

String.Concat(Enumerable.Range(0, 4).Select(_ => "Hello").ToArray())

Upvotes: 2

Jronny
Jronny

Reputation: 2284

Here's my take on this just for future reference:

    /// <summary>
    /// Repeats a System.String instance by the number of times specified;
    /// Each copy of thisString is separated by a separator
    /// </summary>
    /// <param name="thisString">
    /// The current string to be repeated
    /// </param>
    /// <param name="separator">
    /// Separator in between copies of thisString
    /// </param>
    /// <param name="repeatTimes">
    /// The number of times thisString is repeated</param>
    /// <returns>
    /// A repeated copy of thisString by repeatTimes times 
    /// and separated by the separator
    /// </returns>
    public static string Repeat(this string thisString, string separator, int repeatTimes) {
        return string.Join(separator, ParallelEnumerable.Repeat(thisString, repeatTimes));
    }

Upvotes: 0

Will Dean
Will Dean

Reputation: 39500

In .NET 4 you can do this:

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

Upvotes: 264

user51710
user51710

Reputation: 1151

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.

Upvotes: 10

James Curran
James Curran

Reputation: 103495

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

Upvotes: 137

Dmitri Nesteruk
Dmitri Nesteruk

Reputation: 23789

Okay, here's my take on the matter:

public static class ExtensionMethods {
  public static string Multiply(this string text, int count)
  {
    return new string(Enumerable.Repeat(text, count)
      .SelectMany(s => s.ToCharArray()).ToArray());
  }
}

I'm being a bit silly of course, but when I need to have tabulation in code-generating classes, Enumerable.Repeat does it for me. And yeah, the StringBuilder version is fine, too.

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1062640

You'd have to write a method - of course, with C# 3.0 it could be an extension method:

public static string Repeat(this string, int count) {
    /* StringBuilder etc */ }

then:

string bar = "abc";
string foo = bar.Repeat(2);

Upvotes: 9

Tamas Czinege
Tamas Czinege

Reputation: 121294

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

Upvotes: 63

Chris Ballance
Chris Ballance

Reputation: 34337

string Multiply(string input, int times)
{
     StringBuilder sb = new StringBuilder(input.length * times);
     for (int i = 0; i < times; i++)
     {
          sb.Append(input);
     }
     return sb.ToString();
}

Upvotes: 3

Related Questions