2

I want to insert a number of * before a string based on an items depth and I'm wondering if there is a way to return a string repeated Y times. Example:

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 "*********".
oumechtak
  • 19
  • 3

2 Answers2

5

You can use the String constructor:

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

If you really want to repeat a string n-times:

string indent = "***";
string result = String.Concat(Enumerable.Repeat(indent, 3)); // 9 *
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
2

Yes you are looking for PadLeft() Or, in your case even PadRight() will do the trick :

string indent = "".PadLeft(20, '*'); //repeat * 20 times
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
Ashkan Mobayen Khiabani
  • 33,575
  • 33
  • 102
  • 171