NotDan
NotDan

Reputation: 32233

How can I create a string in C# programmatically?

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

Answers (10)

Judah Gabriel Himango
Judah Gabriel Himango

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

Joe Pitz
Joe Pitz

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

Nick Craver
Nick Craver

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

Tom Brothers
Tom Brothers

Reputation: 6017

int NumberOfTabs = 2;
string line = "my line";
string results = line.PadLeft(line.Length + NumberOfTabs, ' ');

Upvotes: 2

Danny T.
Danny T.

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

AndiDog
AndiDog

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

Ben Griswold
Ben Griswold

Reputation: 18381

You could use something like this:

String.Empty.PadRight(NumberOfTabs)

Upvotes: 2

ANeves
ANeves

Reputation: 6385

str = str.PadLeft(str.Length+tabs*4);

Upvotes: 4

Chris McCall
Chris McCall

Reputation: 10407

int i=8;
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append(" ", i);

Upvotes: 8

Codism
Codism

Reputation: 6234

new string(' ', NumberOfTabs )

Upvotes: 6

Related Questions