Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a string in C# programmatically?

Tags:

c#

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?

like image 265
NotDan Avatar asked Mar 09 '10 18:03

NotDan


1 Answers

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);
like image 62
Nick Craver Avatar answered Sep 20 '22 23:09

Nick Craver