HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpCritical

Best way to repeat a character in C#

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
repeatcharacterwaybest

Problem

What is the best way to generate a string of \t's in C#?

I am learning C# and experimenting with different ways of saying the same thing.

Tabs(uint t) is a function that returns a string with t amount of \t's

For example, Tabs(3) returns "\t\t\t"

Which of these three ways of implementing Tabs(uint numTabs) is best?

Of course that depends on what "best" means.

-
The LINQ version is only two lines, which is nice. But are the calls to Repeat and Aggregate unnecessarily time/resource consuming?

-
The StringBuilder version is very clear, but is the StringBuilder class somehow slower?

-
The string version is basic, which means it is easy to understand.

-
Does it not matter at all? Are they all equal?

These are all questions to help me get a better feel for C#.

private string Tabs(uint numTabs)
{
    IEnumerable 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;
}

Solution

What about this:

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


Where n is the number of times you want to repeat the string.

Or better:

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

Code Snippets

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

Context

Stack Overflow Q#411752, score: 1938

Revisions (0)

No revisions yet.