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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/411752/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 02:22:34  来源:igfitidea点击:

Best way to repeat a character in C#

c#.netstring

提问by Alex Baranosky

What it's the best way to generate a string of \t's in C#

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

I am learning C# and experimenting with different ways of saying the same thing.

我正在学习 C# 并尝试用不同的方式来表达同一件事。

Tabs(uint t)is a function that returns a stringwith tamount of \t's

Tabs(uint t)是一个函数,它返回一个string带有t的量\t

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. But are the calls to Repeat and Aggregate unnecessarily time/resource consuming?

  2. The StringBuilderversion is very clear but is the StringBuilderclass somehow slower?

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

  4. Does it not matter at all? Are they all equal?

  1. LINQ 版本只有两行,很好。但是,对 Repeat 和 Aggregate 的调用是否会不必要地消耗时间/资源?

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

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

  4. 一点都不重要吗?他们都是平等的吗?

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

采纳答案by CMS

What about this:

那这个呢:

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

Where nis the number of times you want to repeat the string.

n你想要重复字符串的次数在哪里。

Or better:

或更好:

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

回答by Konrad Rudolph

The best version is certainly to use the builtin way:

最好的版本当然是使用内置方式:

string Tabs(int len) { return new string('\t', len); }

Of the other solutions, prefer the easiest; only if this is proving too slow, strive for a more efficient solution.

在其他解决方案中,选择最简单的;只有当这被证明太慢时,才寻求更有效的解决方案。

If you use a StringBuilderand know its resulting length in advance, then also use an appropriate constructor, this is much more efficient because it means that only one time-consuming allocation takes place, and no unnecessary copying of data.Nonsense: of course the above code is more efficient.

如果你使用 aStringBuilder并提前知道它的结果长度,那么也使用一个合适的构造函数,这会更有效率,因为这意味着只发生一次耗时的分配,并且没有不必要的数据复制。废话:当然上面的代码效率更高。

回答by Ronnie

What about using extension method?

使用扩展方法怎么样?



public static class StringExtensions
{
   public static string Repeat(this char chatToRepeat, int repeat) {

       return new string(chatToRepeat,repeat);
   }
   public  static string Repeat(this string stringToRepeat,int repeat)
   {
       var builder = new StringBuilder(repeat*stringToRepeat.Length);
       for (int i = 0; i < repeat; i++) {
           builder.Append(stringToRepeat);
       }
       return builder.ToString();
   }
}


You could then write :

然后你可以写:

Debug.WriteLine('-'.Repeat(100)); // For Chars  
Debug.WriteLine("Hello".Repeat(100)); // For Strings

Note that a performance test of using the stringbuilder version for simple characters instead of strings gives you a major preformance penality : on my computer the difference in mesured performance is 1:20 between: Debug.WriteLine('-'.Repeat(1000000)) //char version and
Debug.WriteLine("-".Repeat(1000000)) //string version

请注意,对简单字符而不是字符串使用 stringbuilder 版本的性能测试会给您带来主要的性能惩罚:在我的计算机上,测量的性能差异为 1:20:Debug.WriteLine('-'.Repeat(1000000)) //字符版本和
Debug.WriteLine("-".Repeat(1000000)) //字符串版本

回答by Binoj Antony

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

在所有版本的 .NET 中,您可以这样重复字符串:

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.

重复一个角色,new String('\t', count)是你最好的选择。请参阅@CMS 的答案

回答by Dmitri Nesteruk

The answer really depends on the complexity you want. For example, I want to outline all my indents with a vertical bar, so my indent string is determined as follows:

答案实际上取决于您想要的复杂性。例如,我想用竖线勾勒出我所有的缩进,因此我的缩进字符串确定如下:

return new string(Enumerable.Range(0, indentSize*indent).Select(
  n => n%4 == 0 ? '|' : ' ').ToArray());

回答by Rodrick Chapman

Extension methods:

扩展方法:

public static string Repeat(this string s, int n)
{
    return new String(Enumerable.Range(0, n).SelectMany(x => s).ToArray());
}

public static string Repeat(this char c, int n)
{
    return new String(c, n);
}

回答by Ray

Your first example which uses Enumerable.Repeat:

您的第一个示例使用Enumerable.Repeat

private string Tabs(uint numTabs)
{
    IEnumerable<string> tabs = Enumerable.Repeat(
                                 "\t", (int) numTabs);
    return (numTabs > 0) ? 
            tabs.Aggregate((sum, next) => sum + next) : ""; 
} 

can be rewritten more compactly with String.Concat:

可以更紧凑地重写String.Concat

private string Tabs(uint numTabs)
{       
    return String.Concat(Enumerable.Repeat("\t", (int) numTabs));
}

回答by Denys Wessels

How about this:

这个怎么样:

//Repeats a character specified number of times
public static string Repeat(char character,int numberOfIterations)
{
    return "".PadLeft(numberOfIterations, character);
}

//Call the Repeat method
Console.WriteLine(Repeat('\t',40));

回答by Carter Medlin

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?

.net 中是否有重复字符串或字符的内置函数?

回答by bradgonesurfing

Using String.Concatand Enumerable.Repeatwhich will be less expensive than using String.Join

使用String.ConcatEnumerable.Repeat这将比使用更便宜String.Join

public static Repeat(this String pattern, int count)
{
    return String.Concat(Enumerable.Repeat(pattern, count));
}