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

当前回答

对于许多场景,这可能是最简洁的解决方案:

public static class StringExtensions
{
    public static string Repeat(this string s, int n)
        => new StringBuilder(s.Length * n).Insert(0, s, n).ToString();
}

用法是:

text = "Hello World! ".Repeat(5);

这建立在其他答案的基础上(特别是@c0rd)。除了简单之外,它还具有以下特性,不是所有讨论的其他技术都具有这些特性:

重复任意长度的字符串,而不仅仅是字符(根据OP的要求)。 通过存储预分配有效使用StringBuilder。

其他回答

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

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

你可以创建一个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))
  }
}

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

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

这里的信用

对于许多场景,这可能是最简洁的解决方案:

public static class StringExtensions
{
    public static string Repeat(this string s, int n)
        => new StringBuilder(s.Length * n).Insert(0, s, n).ToString();
}

用法是:

text = "Hello World! ".Repeat(5);

这建立在其他答案的基础上(特别是@c0rd)。除了简单之外,它还具有以下特性,不是所有讨论的其他技术都具有这些特性:

重复任意长度的字符串,而不仅仅是字符(根据OP的要求)。 通过存储预分配有效使用StringBuilder。

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

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;