I have a string, and I want to add a number of spaces to the beginning of that string based on an int variable.
I want to do something like this:
int NumberOfTabs = 2;
string line = "my line";
string line = String.Format("{0}{1}", " " * NumberOfTabs, line);
...and now line would have 8 spaces
What is the easiest way to do this?
You can use the String(char, Int32) constructor like this:
string line = String.Format("{0}{1}", new String(' ', NumberofTabs * 4), line);
or a bit more efficient:
string line = String.Concat(new String(' ', NumberofTabs * 4), line);
or, a bit more concise :)
string line = new String(' ', NumberofTabs * 4).Concat(line);
A comment made a good point, if you want to actually have the tab character, just change the ' '
to '\t'
and take out the * 4
like this:
string line = String.Concat(new String('\t', NumberofTabs), line);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With