Best way to repeat a character in C#

What it's 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 "ttt"

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<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; 
    }
    

    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);
    }
    

    In all versions of .NET, you can repeat a string thus:

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

    To repeat a character, new String('t', count) is your best bet. See the answer by @CMS.


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

    Returns

    "abab"

    And

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

    Returns

    "aa"

    from...

    Is there a built-in function to repeat string or char in .net?

    链接地址: http://www.djcxy.com/p/3568.html

    上一篇: 静态只读与常量

    下一篇: 在C#中重复字符的最佳方法