最好重复在C#中字符的方式 [英] Best way to repeat a character in C#

查看:187
本文介绍了最好重复在C#中字符的方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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

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

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

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

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

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

这些都是问题,帮我拿的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 "\t\t\t"

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

Of course that depends on what "best" means.

  1. The LINQ version is only two lines, which is nice. 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?

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

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

这篇关于最好重复在C#中字符的方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆