Reputation: 32233
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?
Upvotes: 6
Views: 2493
Reputation: 60061
Not the best answer by any measure, but here's an amusing one, a little LINQ one-liner:
var result = new string(Enumerable.Repeat(' ', count).Concat("my line").ToArray());
Upvotes: 2
Reputation: 2464
In C# strings are immutable. You should really use the stringbuilder class.
Code examples are listed in the link:
http://msdn.microsoft.com/en-us/library/system.text.stringbuilder.aspx
Upvotes: 3
Reputation: 630627
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);
Upvotes: 19
Reputation: 6017
int NumberOfTabs = 2;
string line = "my line";
string results = line.PadLeft(line.Length + NumberOfTabs, ' ');
Upvotes: 2
Reputation: 1140
You can add tabs at the beginning of your text like this:
line.PadLeft(NumberOfTabs, '\t');
\t being the escape character for "tab" (Inserting a tab character into text using C#)
Upvotes: 2
Reputation: 70228
You can create a new string containing a custom number of spaces. Unfortunately, there's no string multiplication like in Python (" " * 2
). But you can multiply the number of spaces by 4 to get "tabs":
int numberOfTabs = 2;
string line = "my line";
string whitespaces = new string(' ', numberOfTabs * 4);
string s = whitespaces + line;
Upvotes: 0
Reputation: 18381
You could use something like this:
String.Empty.PadRight(NumberOfTabs)
Upvotes: 2
Reputation: 10407
int i=8;
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append(" ", i);
Upvotes: 8