Search code examples
c#stringreplaceescaping

Turning a single quote into an escaped single quote within a string


It pains me to ask this, but, for some reason I have not been able to get this to work (it's late in the day, yes, that's my excuse).

Let's say I have this string:

s = "John's book."

Using the replace method from the object String, I want to turn it into this:

s = "John\'s book."

I would have expected this code to give me what I want:

s = s.Replace("'", "\\'")

But, that results in:

"John\\'s book."

Solution

  • Do this so you don't have to think about it:

    s = s.Replace("'", @"\'");