Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
425 views
in Technique[技术] by (71.8m points)

c# - 在C#中重复字符的最佳方法(Best way to repeat a character in C#)

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("", (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("");

    return sb.ToString();
}  

private string Tabs(uint numTabs)
{
    string output = "";
    for (uint i = 0; i < numTabs; i++)
    {
        output += '';
    }
    return output; 
}
  ask by Alex Baranosky translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What about this:

(那这个呢:)

string tabs = new String('', n);

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

(其中n是您要重复字符串的次数。)

Or better:

(或更好:)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...