How to put unprocessed (escaped) words inside Stri

2019-02-05 17:32发布

问题:

I am formatting a date:

str = String.Format("{0:MMM d m:mm"+yearStr+"}", dt);

I want to put the word "at" after the "d", but I don't want the string to format it. I just want the word "at".

How can I achieve this?

回答1:

You can surround literal strings with quotes, which for longer strings is probably easier and a bit more readable than escaping every character with a backslash:

str = String.Format("{0:MMM d 'at' m:mm"+yearStr+"}", dt);

See Custom Date and Time Format Strings in MSDN Library (search for "Literal string delimiter").

(And did you mean h:mm instead of m:mm?)



回答2:

string.Format(@"{0:MMM d \a\t m:mm" + yearStr + "}", dt);

Note the double escaping - I used a varbatim string so I was able to write \ inside the string as a normal character. The formatting routine for DateTime then interprets this (again) as an escape sequence.

Here is a simpler variant:

string.Format("{0:MMM d} at {0:m:mm" + yearStr + "}", dt);

The first variant might be considered disgusting by some. The latter one is very clear to read, though.



回答3:

Just for fun, but works.

var what=new object[] { "{{{{0:MMM d}}}} {0} {{{{0:m:mm:{{0}}}}}}", "at", yearStr, dt };
var that=what.Aggregate((a, b) => String.Format((String)a, b));

You can merge two lines in one. The at which you want to put between two formats is also parameterized.



回答4:

Using string interpolation (C# 6.0+): (documentation)

var yearStr = "2018";
var dt = DateTime.Now;
var str = $"{dt:MMM d \'at\' H:mm} {yearStr}";

Backslash is optional

var str = $"{dt:MMM d 'at' H:mm} {yearStr}";

see in action: DotnetFiddle