Implementing Repeat() method for strings in C#
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
String.Repeat() method in C#
C# misses some nice and useful string functions that PHP has. One of these is Repeat() method. I don't need it often but there are sometimes utility and integration projects where Repeat() method is needed for data formatting.
Robust and uneffective version
First idea that comes to mind for many developers is rough implementation that gets done fast.
But it doesn't perform very well due to frequent memory allocations.
StringBuilder is implementation of string buffer that allows us to avoid frequent memory allocations by specifying initial buffer size. In fact, we don't need even separate method for Repeat() as it is just one line using StringBuffer.
But there's one problem - we don't control input values here and therefore it's still better to have separate method. Additionally we instantiate StringBuilder even when we don't need it.
The final version of Repeat() method is most intelligent and effective as it has some sanity checks and it creates the buffer with correct size before builder is filled with repeated string.
- string.Repeat() extension method (Gunnar Peipman)
- string.Repeat() – smaller and faster version (Gunnar Peipman)