Coder Perfect

In C#, what is the best approach to repeat a character?

Problem

In C#, what is the most efficient approach to construct a string of t’s?

I’m learning C# and trying out different methods to communicate the same thing.

Tabs(uint t) is a function that returns a string containing t number of ts.

Tabs(3), for example, returns “tttttttttttttttttttttttttt

Which of these three approaches to Tabs(uint numTabs) is the most effective?

Of course, it depends on your definition of “best.”

All of these questions are intended to assist me gain a better understanding of C#.

private string Tabs(uint numTabs)
{
    IEnumerable<string> tabs = Enumerable.Repeat("\t", (int) numTabs);
    return (numTabs > 0) ? tabs.Aggregate((sum, next) => sum + next) : ""; 
}  

private string Tabs(uint numTabs)
{
    StringBuilder sb = new StringBuilder();
    for (uint i = 0; i < numTabs; i++)
        sb.Append("\t");

    return sb.ToString();
}  

private string Tabs(uint numTabs)
{
    string output = "";
    for (uint i = 0; i < numTabs; i++)
    {
        output += '\t';
    }
    return output; 
}

Asked by Alex Baranosky

Solution #1

What about this:

string tabs = new string('\t', n);

Where n is the number of times the string to be repeated.

Or better:

static string Tabs(int n)
{
    return new string('\t', n);
}

Answered by Christian C. Salvadó

Solution #2

string.Concat(Enumerable.Repeat("ab", 2));

Returns

And

string.Concat(Enumerable.Repeat("a", 2));

Returns

from…

Is there a built-in function in.net for repeating a string or char?

Answered by Carter Medlin

Solution #3

You can repeat a string in all versions of.NET by typing:

public static string Repeat(string value, int count)
{
    return new StringBuilder(value.Length * count).Insert(0, value, count).ToString();
}

new String(‘t’, count) is the best way to repeat a character. See @CMS’s response.

Answered by Binoj Antony

Solution #4

The best option is to use the built-in method:

string Tabs(int len) { return new string('\t', len); }

Prefer the simplest option above the others; only if this is too slow, look for a more efficient one.

If you use a StringBuilder and know the length of the result in advance, then use an appropriate constructor, you’ll save a lot of time because there will be just one time-consuming allocation and no wasteful data copying. Nonsense: the above code is, without a doubt, more efficient.

Answered by Konrad Rudolph

Solution #5

Extension methods:

public static string Repeat(this string s, int n)
{
    return new String(Enumerable.Range(0, n).SelectMany(x => s).ToArray());
}

public static string Repeat(this char c, int n)
{
    return new String(c, n);
}

Answered by Rodrick Chapman

Post is based on https://stackoverflow.com/questions/411752/best-way-to-repeat-a-character-in-c-sharp