首页 文章

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

提问于
浏览
648

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

我正在学习C#并尝试不同的方式来说同样的事情 .

Tabs(uint t) 是一个返回 stringt \t 的函数

例如 Tabs(3) 返回 "\t\t\t"

实现 Tabs(uint numTabs) 的这三种方式中哪一种最好?

当然,这取决于“最佳”的含义 .

  • LINQ版只有两行,很不错 . 但重复和聚合的调用是否会不必要地耗费时间/资源?

  • StringBuilder 版本非常清楚,但是 StringBuilder 类的速度有点慢吗?

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

  • 这根本不重要吗?它们都是平等的吗?

这些都是帮助我更好地了解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; 
}

19 回答

  • 112

    我知道这个问题已经有五年了,但有一种简单的方法可以重复一个甚至可以在.Net 2.0中运行的字符串 .

    要重复一个字符串:

    string repeated = new String('+', 3).Replace("+", "Hello, ");
    

    返回

    “你好,你好,你好,”

    要将字符串重复为数组:

    // Two line version.
    string repeated = new String('+', 3).Replace("+", "Hello,");
    string[] repeatedArray = repeated.Split(',');
    
    // One line version.
    string[] repeatedArray = new String('+', 3).Replace("+", "Hello,").Split(',');
    

    返回

    {“你好”,“你好”,“你好”,“”}

    把事情简单化 .

  • 109

    您可以创建扩展方法

    static class MyExtensions
    {
        internal static string Repeat(this char c, int n)
        {
            return new string(c, n);
        }
    }
    

    然后你可以像这样使用它

    Console.WriteLine('\t'.Repeat(10));
    
  • 1
    var str = new string(Enumerable.Repeat('\t', numTabs).ToArray());
    
  • 15

    那这个呢:

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

    其中 n 是您想要重复字符串的次数 .

    或更好:

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

    扩展方法:

    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);
    }
    
  • 16

    最好的版本肯定是使用内置方式:

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

    在其他解决方案中,更喜欢最简单;只有当这证明太慢时,才能争取更有效的解决方案 .

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

  • 40

    这个怎么样:

    //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));
    
  • 58

    而另一种方法

    new System.Text.StringBuilder().Append('\t', 100).ToString()
    
  • 19
    string.Concat(Enumerable.Repeat("ab", 2));
    

    返回

    “abab”

    string.Concat(Enumerable.Repeat("a", 2));
    

    返回

    “aa”

    从...

    Is there a built-in function to repeat string or char in .net?

  • 8

    虽然与之前的建议非常相似,但我希望保持简单并应用以下内容:

    string MyFancyString = "*";
    int strLength = 50;
    System.Console.WriteLine(MyFancyString.PadRight(strLength, "*");
    

    标准.Net真的,

  • 2

    答案实际上取决于您想要的复杂程度 . 例如,我想用竖线标记所有缩进,所以我的缩进字符串确定如下:

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

    毫无疑问,接受的答案是重复单个角色的最佳和最快的方式 .

    Binoj Anthony的回答是一种简单而有效的方法来重复一个字符串 .

    但是,如果你不介意多一些代码,你可以使用我的数组填充技术来更快地有效地创建这些字符串 . 在我的比较测试中,下面的代码在StringBuilder.Insert代码的大约35%的时间内执行 .

    public static string Repeat(this string value, int count)
    {
        var values = new char[count * value.Length];
        values.Fill(value.ToCharArray());
        return new string(values);
    }
    
    public static void Fill<T>(this T[] destinationArray, params T[] value)
    {
        if (destinationArray == null)
        {
            throw new ArgumentNullException("destinationArray");
        }
    
        if (value.Length > destinationArray.Length)
        {
            throw new ArgumentException("Length of value array must not be more than length of destination");
        }
    
        // set the initial array value
        Array.Copy(value, destinationArray, value.Length);
    
        int copyLength, nextCopyLength;
    
        for (copyLength = value.Length; (nextCopyLength = copyLength << 1) < destinationArray.Length; copyLength = nextCopyLength)
        {
            Array.Copy(destinationArray, 0, destinationArray, copyLength, copyLength);
        }
    
        Array.Copy(destinationArray, 0, destinationArray, copyLength, destinationArray.Length - copyLength);
    }
    

    有关此阵列填充技术的更多信息,请参阅Fastest way to fill an array with a single value

  • 22

    试试这个:

    • 添加Microsoft.VisualBasic引用

    • 使用:String result = Microsoft.VisualBasic.Strings.StrDup(5,"hi");

    • 让我知道它是否适合您 .

  • 1

    对我来说很好:

    public static class Utils
    {
        public static string LeftZerosFormatter(int zeros, int val)
        {
            string valstr = val.ToString();
    
            valstr = new string('0', zeros) + valstr;
    
            return valstr.Substring(valstr.Length - zeros, zeros);
        }
    }
    
  • 1246

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

    public static string Repeat(string value, int count)
    {
        return new StringBuilder(value.Length * count).Insert(0, value, count).ToString();
    }
    

    要重复一个角色, new String('\t', count) 是你最好的选择 . 见the answer by @CMS .

  • 0

    使用 String.ConcatEnumerable.Repeat 比使用 String.Join 便宜

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

    那么使用扩展方法呢?


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

    然后你可以写:

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

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

  • 1

    假设你要重复'\ t'次数,你可以使用;

    String.Empty.PadRight(n,'\t')
    
  • 4

    你的第一个使用 Enumerable.Repeat 的例子:

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

    可以用 String.Concat 更紧凑地重写:

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

相关问题