How to put unprocessed (escaped) words inside String.Format

北战南征 提交于 2019-11-29 11:32:01

问题


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



来源:https://stackoverflow.com/questions/15724183/how-to-put-unprocessed-escaped-words-inside-string-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!