简体   繁体   中英

How to escape quotes with string.replace

Not sure my brain has completely started today...

I would need to escape defined quotation marks ( " or ' ) in a string provided by the user, so depending on selected char the transformation should look like follows:

"I'm not so \\"stupid\\", am I?" => "I\\\\'m not so \\"stupid\\", am I?"
"I'm not so \\"stupid\\", am I?" => "I'm not so \\\\\\"stupid\\\\\\", am I?"

Trying to use string.Replace(string, string) drives me a little bit crazy, because it still refuses to perform the desired replacements (no additional backslashes are inserted to the result). And I still refuse to do it manually via loop ;)

Dictionary<Type, char> qString;            // ...
valueStr = "I'm not so \"stupid\", am I?"; // Illustation only, in reality there is some user input used
// ...
string escFrom = qString[type].ToString(); // Make string from the quotation mark
string escTo   = "\\" + escFrom;           // Add the escape to it
valueStr.Replace(escFrom, escTo);          // Try to replace it

Could you please help me with the mentioned startup completion?

Is there any obvious error I'm doing and not seeing?
Is there any hack like "safe" strings or any "culture" related stuff?

你需要分配结果:

valueStr=valueStr.Replace(escFrom, escTo);  

The Replace method doesn't change the string, you have to assign the result of the method call to a string.

You need to escape backslashes also, so it would be:

string escFrom = qString[type].ToString();
string escTo = "\\" + escFrom;
valueStr = valueStr.Replace("\\", "\\\\").Replace(escFrom, escTo);

If you just wand to replace characters, it could be done with the Replace method, where you would have to use its return value; however I second the comments above that the approach might not be suitable, of course depending on what you are finally trying to achieve.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM