Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to better rewrite this repeat function

I have the following function that takes a string as parameter and repeats it a number of times (also a parameter). I feel like this is something that's already in the framework or at least could be done better. Any suggestions?

private string chr(string s, int repeat)
{
    string result = string.Empty;
    for (int i = 0; i < repeat; i++)
    {
        result += s;
    }
    return result;
}
like image 457
AngryHacker Avatar asked Jul 01 '10 20:07

AngryHacker


2 Answers

The most important improvement you could make to your function is to give it a descriptive name.

like image 65
Daniel Earwicker Avatar answered Sep 28 '22 12:09

Daniel Earwicker


Not the most efficient, but concise:

.NET 4:

String.Join(String.Empty, Enumerable.Repeat(s, repeat));

.NET 3.0/3.5:

String.Join(String.Empty, Enumerable.Repeat(s, repeat).ToArray());
like image 24
Julien Lebosquain Avatar answered Sep 28 '22 10:09

Julien Lebosquain