Escaping single quote in String.Format()

走远了吗. 提交于 2019-12-18 03:03:30

问题


I have been all over the 'tubes and I can't figure this one out. Might be simple.

The following String.Format call:

return dt.ToString("MMM d yy 'at' H:mmm");

Correctly returns this:

Sep 23 08 at 12:57

Now let's say I want to add a single quote before the year, to return this:

Sep 23 '08 at 12:57

Since the single quote is a reserved escape character, how do I escape the single quote to get it to display?

I have tried double, triple, and quad single quotes, with no luck.


回答1:


You can escape it using a backslash which you will have to escape. Either

return dt.ToString(@"MMM d \'yy 'at' H:mmm");

or

return dt.ToString("MMM d \\'yy 'at' H:mmm");



回答2:


You could just use the HTML entity, if it's for HTML.

-- Edit

'

-- Edit

Just to make this post not wrong, as everyone else has noted, escaping works fine :)

string s = t.ToString("MMM d \\'yy 'at' H:mmm");

And that's the last time I don't test something based on who is posting :)




回答3:


I don't like the C# @ strings unless I really have to use them so I would actually go with this.

return dt.ToString("MMM d \\'yy 'at' H:mmm");

It's just a preference though for which you find easier to "read".



来源:https://stackoverflow.com/questions/1351074/escaping-single-quote-in-string-format

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