Implementing Repeat() method for strings in C#

gpeipman
1,098 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
using System;
class Hello
{
static void Main()
{
Console.WriteLine("123".Repeat(3));
}
}
public static class StringExtensions
{
public·static·string Repeat(this·string instr, int n)
{
var result = string.Empty;
for (var i = 0; i < n; i++)
result += instr;
return result;
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using System;
using System.Text;
class Hello
{
static void Main()
{
var str = "123";
var n = 3;
var output = new StringBuilder(str.Length * n).Insert(0, str, n).ToString();
Console.WriteLine(output);
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
using System;
using System.Text;
class Hello
{
static void Main()
{
Console.WriteLine("123".Repeat(3));
}
}
public static class StringExtensions
{
public·static·string Repeat(this·string instr, int n)
{
if(n <= 0)
{
return null;
}
if(string.IsNullOrEmpty(instr) || n == 1)
{
return instr;
}
return new StringBuilder(instr.Length * n)
.Insert(0, instr, n)
.ToString();
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

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