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

当前回答

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

其他回答

不知道这将如何执行,但这是一段简单的代码。(我可能让它看起来比实际更复杂。)

int indentCount = 3;
string indent = "---";
string stringToBeIndented = "Blah";
// Need dummy char NOT in stringToBeIndented - vertical tab, anyone?
char dummy = '\v';
stringToBeIndented.PadLeft(stringToBeIndented.Length + indentCount, dummy).Replace(dummy.ToString(), indent);

或者,如果您知道期望的最大层数,则可以声明一个数组并在其中建立索引。你可能想让这个数组是静态的或者是常量。

string[] indents = new string[4] { "", indent, indent.Replace("-", "--"), indent.Replace("-", "---"), indent.Replace("-", "----") };
output = indents[indentCount] + stringToBeIndented;      

我喜欢你给出的答案。我过去也用过同样的方法:

"".PadLeft(3*Indent,'-')

这将实现创建缩进,但技术上的问题是重复一个字符串。如果字符串缩进是像>-<这样的东西,那么这个和接受的答案一样将不起作用。在这种情况下,c0rd使用StringBuilder的解决方案看起来不错,尽管StringBuilder的开销实际上可能不是最高性能的。一种选择是构建一个字符串数组,用缩进字符串填充它,然后连接它。一点点:

int Indent = 2;
        
string[] sarray = new string[6];  //assuming max of 6 levels of indent, 0 based

for (int iter = 0; iter < 6; iter++)
{
    //using c0rd's stringbuilder concept, insert ABC as the indent characters to demonstrate any string can be used
    sarray[iter] = new StringBuilder().Insert(0, "ABC", iter).ToString();
}

Console.WriteLine(sarray[Indent] +"blah");  //now pretend to output some indented line

我们都喜欢聪明的解决方案,但有时简单是最好的。

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

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,否则会出现异常。

添加扩展方法,我正在使用我的所有项目:

public static string Repeat(this string text, int count)
{
    if (!String.IsNullOrEmpty(text))
    {
        return String.Concat(Enumerable.Repeat(text, count));
    }
    return "";
}

希望有人能利用它…

我想要Dan Tao的答案,但是如果你没有使用。net 4.0,你可以这样做:

public static string Repeat(this string str, int count)
{
    return Enumerable.Repeat(str, count)
                     .Aggregate(
                        new StringBuilder(str.Length * count),
                        (sb, s) => sb.Append(s))
                     .ToString();
}