在C#中重复字符的最佳方法

南笙酒味 提交于 2020-10-27 14:07:05

问题:

What it's the best way to generate a string of \\t 's in C# 在C#中生成\\t字符串的最佳方法是什么

I am learning C# and experimenting with different ways of saying the same thing. 我正在学习C#,并尝试用不同的方式说同一件事。

Tabs(uint t) is a function that returns a string with t amount of \\t 's Tabs(uint t)是一个函数,该函数返回t等于\\tstring

For example Tabs(3) returns "\\t\\t\\t" 例如Tabs(3)返回"\\t\\t\\t"

Which of these three ways of implementing Tabs(uint numTabs) is best? 这三种实现Tabs(uint numTabs)方式中哪一种最好?

Of course that depends on what "best" means. 当然,这取决于“最佳”的含义。

  1. The LINQ version is only two lines, which is nice. LINQ版本只有两行,这很好。 But are the calls to Repeat and Aggregate unnecessarily time/resource consuming? 但是,重复和聚合的调用是否不必要地浪费时间/资源?

  2. The StringBuilder version is very clear but is the StringBuilder class somehow slower? StringBuilder版本非常清晰,但StringBuilder类的速度是否稍慢?

  3. The string version is basic, which means it is easy to understand. string版本是基本的,这意味着易于理解。

  4. Does it not matter at all? 没关系吗? Are they all equal? 他们都平等吗?

These are all questions to help me get a better feel for C#. 这些都是可以帮助我更好地理解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; 
}

解决方案:

参考一: https://stackoom.com/question/1j7A/在C-中重复字符的最佳方法
参考二: https://oldbug.net/q/1j7A/Best-way-to-repeat-a-character-in-C
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!