views:

717

answers:

4

In Perl

print "a" x 3;  # aaa

In C#

Console.WriteLine( ??? )
+13  A: 

It depends what you need... there is new string('a',3) for example.

For working with strings; you could just loop... not very interesting, but it'll work.

With 3.5, you could use Enumerable.Repeat("a",3), but this gives you a sequence of strings, not a compound string.

If you are going to use this a lot, you could use a bespoke C# 3.0 extension method:

    static void Main()
    {
        string foo = "foo";
        string bar = foo.Repeat(3);
    }
    // stuff this bit away in some class library somewhere...
    static string Repeat(this string value, int count)
    {
        if (count < 0) throw new ArgumentOutOfRangeException("count");
        if (string.IsNullOrEmpty(value)) return value; // GIGO            
        if (count == 0) return "";
        StringBuilder sb = new StringBuilder(value.Length * count);
        for (int i = 0; i < count; i++)
        {
            sb.Append(value);
        }
        return sb.ToString();
    }
Marc Gravell
Marc dont you think StringBuilder().Insert(0, value, count) is better?
Binoj Antony
Good spot; simply didn't see the overload...
Marc Gravell
+4  A: 

If you only need to repeat a single character (as in your example) then this will work:

Console.WriteLine(new string('a', 3))
GeekyMonkey
Only works for "new string(CHAR, COUNT)", not for strings.
Tom
True, but it fulfills the requirement in the question.
GeekyMonkey
So Perl's repetition operator works only on chars? The fact that he used a string comprising of a single character shouldn't have tipped you off to restrict the answer to that particular example. The question was more general.
Tom
See my other reply for how to do this with strings then.
GeekyMonkey
A: 

If you need to do this with strings like Tom pointed out, then an extension method will do the job nicely.

static class StringHelpers
{
 public static string Repeat(this string Template, int Count)
 {
  string Combined = Template;
  while (Count > 1) {
   Combined += Template;
   Count--;
  }
  return Combined;
 }
}

class Program
{
 static void Main(string[] args)
 {
  string s = "abc";
  Console.WriteLine(s.Repeat(3));
  Console.ReadKey();
 }
GeekyMonkey
For work in a loop like this, it would be adviseable to use StringBuilder... concatenation is fine for 2-or-3, but if somebody asks for "a".Repeat(100) you have a lot of unnecessary strings to collect.
Marc Gravell
That's true. There is some point in which StringBuilder becomes more efficient. I've heard that it's around 10. In the example given he had 3, so I assumed it would be small. If you want to cover a wider range, then putting in an "if" and using StringBuilder for over 10 would be more efficient.
GeekyMonkey
+3  A: 

Well in all version of .NET to repeat a string you could always do this

public static string Repeat(string value, int count)
{
  return new StringBuilder().Insert(0, value, count).ToString();
}
Binoj Antony