Question

I have a Little Problem here. Im trying to replace the Character ' with \'

I tried string replace method in the following ways:

1.

string test = "HISTOIRE D'O, CHAPITRE II";
test = test.Replace("'","\'");

Nothing Changed in the String test is the same as declared

2.

string test = "HISTOIRE D'O, CHAPITRE II";
test = test.Replace("'","\\'");

This Formats my string like this "HISTOIRE D\\'O, CHAPITRE II";

Found nothing yet on Google etc.

Thanks for every help.

Était-ce utile?

La solution

Your second code is correct.

This Formats my string like this "HISTOIRE D\'O, CHAPITRE II";

No, it really doesn't. That's how it looks in the debugger, but if you dump it to a console or something similar, you'll see there's only a single backslash.

As an alternative, you could use a verbatim string literal:

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

Autres conseils

Your second case seems correct. Looks like this is only how looks like in degubber. Try to write on console and you will see the expected result.

enter image description here

You can use verbtaim string literal instead;

string test = "HISTOIRE D'O, CHAPITRE II";
test = test.Replace("'", @"\'");

Your second example is working, but when you look at the result in the debugger it "helpfully" escapes the backslash by adding a new backslash to it.

If you print the result to a console window you should see what you are expecting.

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

This should do the trick:

string test = "HISTOIRE D'O, CHAPITRE II";
test = test.Replace("'", @"\'");
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top