Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace ' with \' in C#

Tags:

c#

In this variable, i would like to add some \ before every '.

string html = 
    "<a href=\"annee-prochaine.html\">Calendrier de l'annee prochaine</a>"

html = html.Replace("'", "\'"); //No change
html = html.Replace("\'", "\'"); //No change

html = html.Replace("\'", "\\'");
//html => <a href=\"annee-prochaine.html\">Calendrier de l\\'annee prochaine</a>
html = html.Replace("\'", @"\'");
//html => <a href=\"annee-prochaine.html\">Calendrier de l\\'annee prochaine</a>

I would like to get that after Replace :

//html => <a href=\"annee-prochaine.html\">Calendrier de l\'annee prochaine</a>

Any ideas ?

Thanks!

like image 863
Ceryl Avatar asked Nov 26 '12 16:11

Ceryl


People also ask

Is there any Replace function in C?

Algorithm to Replace string in C Accept the string, with which to replace the sub-string. If the substring is not present in the main string, terminate the program. If the substring is present in the main string then continue.

How do you find and replace a word in a string in C?

The fastest way would be to allocate a new string that is strlen (s) - strlen (word) + strlen (rpwrd) + 1 . Then use the strstr function to find the word to be replaced and copy up to that point into a new string, append the new word, then copy the rest of the original sentence into a new string.

Can we modify string in C?

No you can still use the object allocated on stack.


4 Answers

I strongly suspect that you're looking at the strings in the debugger, which is why you're seeing doubled backslashes.

This version is absolutely fine:

html = html.Replace("\'", "\\'");

(The one using the verbatim string literal would be fine too.) Rather than looking at it in the debugger, log it or just serve it, and everything should be fine.

The fact that you're seeing it for the double-quote as well is further evidence of this. For example, this string:

string html = "<a href=\"anne...";

... does not contain a backslash, but your diagnostics are showing it, which is what I'd expect in a debugger.

like image 178
Jon Skeet Avatar answered Oct 14 '22 03:10

Jon Skeet


The backslash character is an escape character, so you either need to put 2 of them, or use the @ string modifier which ignores escaping.

html=html.Replace("'", "\\'"); // this should work
html=html.Replace("'", @"\'"); // or this
like image 31
Nick Larsen Avatar answered Oct 14 '22 03:10

Nick Larsen


 string html = "<a href=\"annee-prochaine.html\">Calendrier de l'annee prochaine</a>"

 html = html.Replace("'",@"\'");
like image 1
3Dave Avatar answered Oct 14 '22 02:10

3Dave


Try this:

html=html.Replace("'", @"\'"); 
like image 1
Felipe Oriani Avatar answered Oct 14 '22 02:10

Felipe Oriani