views:

255

answers:

8

Hello, how can I format a string like this:

string X = "'{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}'",????

I remember I used to be able to put a comma at the end and specify the actual data to assign to {0},{1}, etc.

Any help?

+13  A: 

Use string.Format method such as in:


string X = string.Format("'{0}','{1}','{2}'", foo, bar, baz);
Alfred Myers
And use format specifiers inside the braces to control how the substitued values are formatted, i.e., if bar was 2.34, using {1:0000.0} would cause bar to print as "0002.3"
Charles Bretana
And you don't need the single quotes to delineate literals, anything not inside braces will be output literally
Charles Bretana
I'm formatting an SQL insert statement, that's why I'm using single quotes. :P
Sergio Tapia
A: 

Use string.Format as in

var output = string.Format("'{0}', '{1}'", x, y);
Brian Rasmussen
Just tempting fate aren't you ...
Noon Silk
Sorry I couldn't resist :)
Brian Rasmussen
+1  A: 
String.Format("'{0}', '{1}'", arg0, arg1);
Matt Davis
+1  A: 

The String.Format method accepts a format string followed by one to many variables that are to be formatted. The format string consists of placeholders, which are essentially locations to place the value of the variables you pass into the function.

Console.WriteLine(String.Format("{0}, {1}, {2}", var1, var2, var3));
Mitch Wheat
Console.WriteLine supports that as well, so you can omit the String.Format for that.
Brian Rasmussen
I always, always forget that! Thx.
Mitch Wheat
+1  A: 

Your question is a bit vague, but do you mean:

// declare and set variables val1 and val2 up here somewhere
string X = string.Format("'{0}','{1}'", val1, val2);

Or are you asking for something else?

Philip Rieck
A: 

are you looking for:

String.Format("String with data {0}, {1} I wish to format", "Foo", "Bar");

would result in

"String with data Foo, Bar I wish to format"

+5  A: 

An alternative is to use Join, if you have the values in a string array:

string x = "'" + String.Join("','", valueArray) + "'";

(Just wanted to be different from the 89724362 users who will show you how to use String.Format... ;)

Guffa
+1  A: 

use string.format, and put individual format specifiers inside the braces, after the number and a colon, as in

   string s = string.Format(
        " {0:d MMM yyyy} --- {1:000} --- {2:#,##0.0} -- {3:f}",
        DateTime.Now, 1, 12345.678, 3e-6);

and, as you can see from the example, you don;t need the single quotes to delineate literals, anything not inside braces will be output literally

Charles Bretana