Implementing Repeat() method for strings in C#

gpeipman
16.8K views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

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.

Using StringBuilder

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.

References

Open Source Your Knowledge: become a Contributor and help others learn. Create New Content