Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the C# equivalent of Perl's repetition operator?

Tags:

string

c#

perl

In Perl

print "a" x 3;  # aaa

In C#

Console.WriteLine( ??? )
like image 635
Ed Guiness Avatar asked Nov 17 '08 15:11

Ed Guiness


People also ask

What is C used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is C language in simple words?

C is a structured, procedural programming language that has been widely used both for operating systems and applications and that has had a wide following in the academic community. Many versions of UNIX-based operating systems are written in C.

Why is C called C?

C is a general purpose computer programming language developed in 1972 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system. It was named 'C' because many of its features were derived from an earlier language called 'B'.


2 Answers

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();
    }
like image 169
Marc Gravell Avatar answered Nov 15 '22 22:11

Marc Gravell


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

Console.WriteLine(new string('a', 3))
like image 22
GeekyMonkey Avatar answered Nov 15 '22 22:11

GeekyMonkey