返回重复多次的字符串

时间:2018-11-13 15:23:37

标签: c#

我想根据项目的深度在字符串前插入*号,我想知道是否有办法返回重复Y次的字符串。示例:

string indent = "***";
Console.WriteLine(indent.Redraw(0)); //would print nothing.
Console.WriteLine(indent.Redraw(1)); //would print "***".
Console.WriteLine(indent.Redraw(2)); //would print "******".
Console.WriteLine(indent.Redraw(3)); //would print "*********".

2 个答案:

答案 0 :(得分:5)

您可以使用String constructor

string result = new String('*', 9); // 9 *

如果您真的想重复一个字符串n次:

string indent = "***";
string result = String.Concat(Enumerable.Repeat(indent, 3)); // 9 *

答案 1 :(得分:2)

是的,您正在寻找PadLeft(),或者就您而言,PadRight()也会达到目的:

string indent = "".PadLeft(20, '*'); //repeat * 20 times