我试图在基于项深度的字符串之前插入一定数量的缩进,我想知道是否有一种方法可以返回一个重复X次的字符串。例子:

string indent = "---";
Console.WriteLine(indent.Repeat(0)); //would print nothing.
Console.WriteLine(indent.Repeat(1)); //would print "---".
Console.WriteLine(indent.Repeat(2)); //would print "------".
Console.WriteLine(indent.Repeat(3)); //would print "---------".

当前回答

如果你只想重复相同的字符,你可以使用string构造函数接受一个字符和重复次数new string (char c, int count)。

例如,重复五次破折号:

string result = new String('-', 5);
Output: -----

其他回答

使用字符串。PadLeft,如果你想要的字符串只包含一个字符。

public static string Indent(int count, char pad)
{
    return String.Empty.PadLeft(count, pad);
}

这里的信用

你可以重复你的字符串(如果它不是一个单一的字符)并连接结果,像这样:

String.Concat(Enumerable.Repeat("---", 5))

没想到居然没人走老路。 我并没有对这段代码做任何声明,只是为了好玩:

public static string Repeat(this string @this, int count)
{
    var dest = new char[@this.Length * count];
    for (int i = 0; i < dest.Length; i += 1)
    {
        dest[i] = @this[i % @this.Length];
    }
    return new string(dest);
}

字符串和字符[版本1]

string.Join("", Enumerable.Repeat("text" , 2 ));    
//result: texttext

字符串和字符[版本2]:

String.Concat(Enumerable.Repeat("text", 2));
//result: texttext

字符串和字符[版本3]

new StringBuilder().Insert(0, "text", 2).ToString(); 
//result: texttext

识字课只有:

'5' * 3; 
//result: 555

识字课只有:

new string('5', 3);
//result: 555

扩展方法:

(工作更快-更好的WEB)

public static class RepeatExtensions
{
    public static string Repeat(this string str, int times)
    {
        var a = new StringBuilder();
        
        //Append is faster than Insert
        ( () => a.Append(str) ).RepeatAction(times) ;
        
        return a.ToString();
    }

    public static void RepeatAction(this Action action, int count)
    {
        for (int i = 0; i < count; i++)
        {
            action();
        }
    }

}

用法:

 var a = "Hello".Repeat(3); 
 //result: HelloHelloHello

使用新字符串。创建函数时,我们可以预先分配合适的大小,并使用Span<char>在循环中复制单个字符串。

我怀疑这可能是最快的方法,因为根本没有额外的分配:字符串被精确分配。

 public static string Repeat(this string source, int times)
 {
     return string.Create(source.Length * times, source, RepeatFromString);
 }
 
 private static void RepeatFromString(Span<char> result, string source)
 {
     ReadOnlySpan<char> sourceSpan = source.AsSpan();
     for (var i = 0; i < result.Length; i += sourceSpan.Length)
         sourceSpan.CopyTo(result.Slice(i, sourceSpan.Length));
 }

dotnetfiddle