Gunnar Peipman's ASP.NET blog

ASP.NET, C#, SharePoint, SQL Server and general software development topics.

Sponsors

News

 
 
 
DZone MVB

Links

Social

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

Comments

Paulo Correia said:

Hi,

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

Best regards

Paulo Correia

# May 12, 2009 10:37 AM

ca8msm said:

PadLeft or PadRight would have worked.

# May 12, 2009 11:25 AM

Mark Hildreth said:

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

# May 12, 2009 12:30 PM

Dave said:

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’.  

# May 12, 2009 10:45 PM

rajbk said:

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

# May 13, 2009 10:25 AM

whichman said:

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

# May 13, 2009 11:37 AM