我试图在基于项深度的字符串之前插入一定数量的缩进,我想知道是否有一种方法可以返回一个重复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 "---------".

当前回答

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

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

这里的信用

其他回答

        string indent = "---";
        string n = string.Concat(Enumerable.Repeat(indent, 1).ToArray());
        string n = string.Concat(Enumerable.Repeat(indent, 2).ToArray());
        string n = string.Concat(Enumerable.Repeat(indent, 3).ToArray());

字符串和字符[版本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

我没有足够的代表来评论亚当的回答,但在我看来,最好的方法是这样的:

public static string RepeatString(string content, int numTimes) {
        if(!string.IsNullOrEmpty(content) && numTimes > 0) {
            StringBuilder builder = new StringBuilder(content.Length * numTimes);

            for(int i = 0; i < numTimes; i++) builder.Append(content);

            return builder.ToString();
        }

        return string.Empty;
    }

您必须检查numTimes是否大于0,否则会出现异常。

另一种方法是将string视为IEnumerable<char>,并使用通用扩展方法将集合中的项乘以指定的因子。

public static IEnumerable<T> Repeat<T>(this IEnumerable<T> source, int times)
{
    source = source.ToArray();
    return Enumerable.Range(0, times).SelectMany(_ => source);
}

在你的例子中:

string indent = "---";
var f = string.Concat(indent.Repeat(0)); //.NET 4 required
//or
var g = new string(indent.Repeat(5).ToArray());

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

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

这里的信用