我试图根据项目深度在字符串之前插入一定数量的缩进,并且我想知道是否有办法返回重复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 "---------".
如果只打算重复相同的字符,则可以使用接受char和重复次数的字符串构造函数new String(char c, int count)。
new String(char c, int count)
例如,要重复五次破折号:
string result = new String('-', 5); Output: -----