.net 在 String.Format() 中转义单引号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1351074/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Escaping single quote in String.Format()
提问by Jeff Atwood
I have been all over the 'tubes and I can't figure this one out. Might be simple.
我一直在'管子里,我无法弄清楚这个。可能很简单。
The following String.Formatcall:
以下String.Format调用:
return dt.ToString("MMM d yy 'at' H:mmm");
Correctly returns this:
正确返回:
Sep 23 08 at 12:57
08 年 9 月 23 日 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
2008 年 9 月 23 日 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.
我试过双、三和四单引号,但没有成功。
回答by Martin Liversage
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");
回答by Noon Silk
You could just use the HTML entity, if it's for HTML.
您可以只使用 HTML 实体,如果它用于 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 :)
这是我最后一次不根据发帖人来测试内容:)
回答by Robin Day
I don't like the C# @ strings unless I really have to use them so I would actually go with this.
我不喜欢 C# @ 字符串,除非我真的必须使用它们,所以我实际上会使用它。
return dt.ToString("MMM d \'yy 'at' H:mmm");
It's just a preference though for which you find easier to "read".
不过,这只是一种偏好,您会发现它更容易“阅读”。

