string.Repeat() extension method

I needed str_repeat() functionality in one of my C# methods. As .Net currently doesn’t offer it I wrote my own Repeat() extension method for strings. Here you can find C# and VB.NET versions. Make sure you put the method inside static class.

 

NB! This blog is moved to gunnarpeipman.com

Click here to go to article

6 Comments

  • Hi,

    You could use the StringBuilder class inside the Repeat method. Whould have better performance ;)

    Best regards
    Paulo Correia

  • PadLeft or PadRight would have worked.

  • Just FYI - string concatenation can be pretty inefficient as far as memory usage and processing are concerned. As n grows large, you may run into issues. Here's another option:

    public static string Repeat(this string instr, int n){
    int totalLength = instr.length * n;
    ScringBuilder resultString = new StringBuilder(totalLength);
    for(var i=0; i<n; i++)
    resultString.Append(instr);
    return resultString.ToString();
    }

    This way, you actually initialize the string builder with the correct initial capacity and then fill it - thus relieving the need for the string builder to resize it's internal array. This should help the memory usage and processing farily consistent as n gets larger and larger. Hope that helps,

    -Mark

  • As Mark points out strings are immutable which can cause string concatenation inefficient. Whenever you concatenate strings a new string object is instantiated, the contents of the original string are copied to the new object, and the original string is disposed. One thing I am wondering about Mark’s code is how does the performance of the for loop compare to using the insert method that Gunnar showed in the original post. The performance difference for using a string builder compared to concatenation and the insert method compared to the for loop are more than likely going to be negligible when repeating small strings and or a small value for ‘n’.

  • String has a constructor that allows you to define the number of times a char occurs.

    string s = new String('a', 10);
    Console.WriteLine(s);

    output:
    aaaaaaaaaa

    Raj

  • @rajbk
    String has a constructor that allows you to define the number of times a char occurs but it only allows chars not strings.

    You cannot do this: var str = new String("abc",5);

    But you can do this: var str = "abc".Repeat(5);

Comments have been disabled for this content.