简体   繁体   中英

String formatting in C#

I'm working my way through a string formatting "cheat sheet", so that I can see how different string formatting arguments affect the string output. Whilst working with DateTime string formatting arguments, I wrote this little test:

char[] dtFormats = new char[] { 'd', 'D', 'f', 'F', 'g', 'G', 'm', 'o', 'r', 's', 't', 'T', 'u', 'U', 'y' };
foreach (char format in dtFormats)
{
    Console.WriteLine("DateTime format {0} = {1:" + format + "}", format, DateTime.Now);
}

All it does is show all the different formats for a DateTime using each argument.

That aside, I'd like to focus on this:

Console.WriteLine("DateTime format {0} = {1:" + format + "}", format, DateTime.Now);

Now I know that {0} is replaced with format (argument 0) , and {1:?} is replaced with DateTime.Now (argument 1) .

I tried to re-write this like so:

Console.WriteLine("DateTime format {0} = {1:{0}}", format, DateTime.Now);

This raises a FormatException , but I would like to know why you can't nest string place holders inside other format string place holders.

In this case it should replace {0} with the format argument, and {1:{0}} with DateTime.Now , followed by a colon and the format argument.

Is this not possible in C#?

EDIT:

For that matter, why does Console.WriteLine("{{0}}", "Hello World"); result in "{0}" instead of "{Hello World}" ?

How about we simplify this a little? You're trying to nest braces when the syntax states that {{ means a single literal { . This is what you're looking for:

Console.WriteLine("DateTime format {0} = {1}", format, DateTime.Now.ToString(format));

And to answer this question:

For that matter, why does Console.WriteLine("{{0}}", "Hello World"); result in "{0}" instead of "{Hello World}"?

I reiterate that {{ , syntactically means a single literal { .

Now, if you wanted to use the colon syntax, you have that wrong anyway, it works like this {100:C} , that would display 100 in a currency format. But you really don't need to do that here because getting that format to work would be difficult cause you need this {1:{0}} and that's going to fail because of the escape syntax.

It won't work because a double curly }} escapes the curly braces in the formatted string.

As you've found, this:

string.Format("This {{is}} my {{escaped}} curlies");

..is fine (and results in This {is} my {escaped} curlies) .. because they are escaped. If you nest them like you have.. the parser won't know whether to escape or not.

Image being the parser and encountering this:

Console.WriteLine("DateTime format {0} = {1:{0}}", format, DateTime.Now);
/*                                            ^^ Okay, I'll escape this. WAIT!
                                                 .. now I have a two single
                                                 curly open braces. This is
                                                 a badly formatted format string
                                                 now.. FormatException!*/

您可以尝试以下方法:

Console.WriteLine(string.Format("DateTime format {0} = {{1:{0}}}", format), format, DateTime.Now);

在格式内你不能引用任何参数。

A simple proceeding to make sure that you will not have any problem with characters being misundertood is separating what to put in each side: for the left side, just the references to the chunks with the minimum additional information possible; for the right side, as complex chunks as required (not just variables). Example:

Console.WriteLine("DateTime format {0}{1}{2}", format, " = {" + DateTime.Now, ":" + format + "}");

or even:

Console.WriteLine("{0}{1}{2}", "DateTime format " + format, " = {" + DateTime.Now, ":" + format + "}");

You might even rely on variables:

string chunk1 = "DateTime format " + format;
string chunk2 = " = {" + DateTime.Now;
string chunk3 = ":" + format + "}";
Console.WriteLine("{0}{1}{2}", chunk1, chunk2, chunk3);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM