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

当前回答

如果你使用。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构造函数接受一个字符和重复次数new string (char c, int count)。

例如,重复五次破折号:

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

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

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

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

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

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;      

没想到居然没人走老路。 我并没有对这段代码做任何声明,只是为了好玩:

public static string Repeat(this string @this, int count)
{
    var dest = new char[@this.Length * count];
    for (int i = 0; i < dest.Length; i += 1)
    {
        dest[i] = @this[i % @this.Length];
    }
    return new string(dest);
}