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

其他回答

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

"".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

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

你可以创建一个ExtensionMethod来做这件事!

public static class StringExtension
{
  public static string Repeat(this string str, int count)
  {
    string ret = "";

    for (var x = 0; x < count; x++)
    {
      ret += str;
    }

    return ret;
  }
}

或者使用@丹涛解决方案:

public static class StringExtension
{
  public static string Repeat(this string str, int count)
  {
    if (count == 0)
      return "";

    return string.Concat(Enumerable.Repeat(indent, N))
  }
}

最高性能的字符串解决方案

string result = new StringBuilder().Insert(0, "---", 5).ToString();
public static class StringExtensions
{
    public static string Repeat(this string input, int count)
    {
        if (string.IsNullOrEmpty(input) || count <= 1)
            return input;

        var builder = new StringBuilder(input.Length * count);

        for(var i = 0; i < count; i++) builder.Append(input);

        return builder.ToString();
    }
}

另一种方法是将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());