Escaping single quote in String.Format()
Asked Answered
P

3

32

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.

Pavel answered 29/8, 2009 at 10:24 Comment(0)
Z
40

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");
Zeena answered 29/8, 2009 at 10:30 Comment(4)
in my defense, I became mesmerized by the way you have to do {{{ to escape curlies in a String.Format() and temporarily lost my mind.. thanks!Pavel
The % characters are unnecessary in this case as %d and %H are combined with other format patterns. It makes it a bit clearer without them.Nickell
@Martin I don't know if this is related or if I should open a new question, but how can I make this work? <asp:Label ID="Label1" runat="server" Text='<%# Eval("MyDate", "{0:MMM d yy 'at' H:mmm}")%>'> currently I get an error, I guess because the sigle quotes of 'at'Mou
nevermind, I found the solution here https://mcmap.net/q/454877/-how-to-use-single-quotes-in-eval-format-stringMou
V
6

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

-- Edit

&#39;

-- 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 :)

Vegetative answered 29/8, 2009 at 10:26 Comment(0)
V
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".

Vancouver answered 29/8, 2009 at 10:34 Comment(2)
Try writing a unit test that tests a class that detects escaped characters and processes them. You'll start loving @ strings in a big hurry.Conti
After 5 minutes writing regexes, I started to love @ strings too. :-)Tiemannite

© 2022 - 2024 — McMap. All rights reserved.