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

其他回答

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

string result = new StringBuilder().Insert(0, "---", 5).ToString();

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

例如,重复五次破折号:

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

重复打印一行。

Console.Write(new string('=', 30) + "\n");

==============================

如果你使用。net 4.0,你可以使用字符串。与enumerable连接。重复。

int N = 5; // or whatever
Console.WriteLine(string.Concat(Enumerable.Repeat(indent, N)));

否则我会用亚当的答案。

我通常不建议使用Andrey的答案的原因很简单,ToArray()调用引入了多余的开销,而Adam建议的StringBuilder方法可以避免这些开销。也就是说,至少它不需要。net 4.0就能工作;而且它又快又简单(如果效率不是太重要的话,也不会要了你的命)。

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

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