最好重复在C#中字符的方式字符、方式

2023-09-02 01:26:52 作者:爱情很抽象▂_

什么是生成 t 的字符串的在C#中的最佳方式

我学习C#和与说同样的事情不同的方式尝试。

标签(UINT T)是一个函数,返回字符串 T 金额 t

例如标签(3)返回 t t t的

这三种方式实施标签(UINT numTabs)的是最好的?

当然,这取决于什么最好的手段。

LINQ的版本是只有两行,这是很好的。但对重复和通话总时不必要/资源消耗?

的StringBuilder 的版本是很清楚的,但是是的StringBuilder 类莫名其妙地慢?

字符串的版本是基本的,这意味着它是很容易理解。

这岂不是在所有问题?他们都是一样的吗?

这些都是问题,帮我拿的C#一个更好的感觉。

 私人字符串标签(UINT numTabs)
{
    IEnumerable的<字符串>标签= Enumerable.Repeat( t的,(INT)numTabs);
    返回(numTabs大于0)? tabs.Aggregate((总和,明​​年)=>总和+下一个):;
}

私人字符串标签(UINT numTabs)
{
    StringBuilder的SB =新的StringBuilder();
    对于(UINT I = 0; I< numTabs;我++)
        sb.Append( t的);

    返回sb.ToString();
}

私人字符串标签(UINT numTabs)
{
    字符串输出=;
    对于(UINT I = 0; I< numTabs;我++)
    {
        输出+ =' T';
    }
    返回输出;
}
 
分别用字符数组和字符指针作函数参数两种方法编程实现在字符串中删除与某字符相同的字符

解决方案

怎么样的:

 字符串的选项卡=新的String( t,N);
 

或者更好的:

 静态字符串标签(INT N)
{
    返回新的String( t,N);
}
 

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

Or better:

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