Movieboy
Movieboy

Reputation: 373

How to insert another variable into string with a Space? C#

I know this is a very stupid and elementary question, but I really have no idea on other ways to accomplish this.

Now I know I can insert spaces within the text like my example below.

int num = some numerical value;
status.Text = "Successfully Deleted"+ " " + num + " " + "Files";

However, I'm wondering is there a neater way to do this. I always done it this way, but I'm wondering whether there's an easier/neater way to it. Thanks.

Upvotes: 2

Views: 140

Answers (2)

Tim S.
Tim S.

Reputation: 56536

More options:

status.Text = "Successfully Deleted " + num + " Files";

Or:

public static string SurroundWithSpaces(this object o)
{
    return " " + o + " ";
}
status.Text = "Successfully Deleted" + num.SurroundWithSpaces() + "Files";

Upvotes: 0

Furqan Safdar
Furqan Safdar

Reputation: 16698

Using String class:

int num = 5;
status.Text = String.Format("Successfully Deleted {0} Files", num);

Using StringBuilder class:

int num = 5;
StringBuilder sb = new StringBuilder();
sb.AppendFormat("Successfully Deleted {0} Files", num);
status.Text = sb.ToString();

Upvotes: 10

Related Questions