技术问询:如何将字符串中的"替换为""?str.replace尝试未果
解决C#字符串中双引号替换为双份双引号的问题
嘿,我来帮你搞定这个问题!你遇到的情况其实有几个小细节没注意到,咱们一步步捋清楚:
首先,你的初始字符串定义有语法错误
在C#的逐字字符串(用@开头的字符串)里,双引号不能直接写",必须用两个双引号""来转义,不然编译器会直接报错。所以你原来的字符串定义应该改成这样:
string str = @"<?xml version=""1.0"" encoding=""utf-8""?> <soap:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/""> <soap:Body> <GetResources xmlns=""http://www.example.com""> </GetResources> </soap:Body> </soap:Envelope>";
为什么str.Replace('"', '""')没效果?
这里有两个关键问题:
- 字符版本的
Replace不支持多字符替换:你用的是char类型的重载方法Replace(char oldChar, char newChar),但'""'不是合法的单个字符(char只能存一个字符),这个代码其实编译都通不过! - 字符串不可变性:C#里的字符串是不可变的,
Replace方法不会修改原字符串,而是返回一个全新的字符串实例。如果你只是调用方法却不把返回值赋值给变量,原字符串根本不会变化。
正确的解决方案
用字符串版本的Replace方法,并且接收返回的新字符串:
// 先修正初始字符串 string str = @"<?xml version=""1.0"" encoding=""utf-8""?> <soap:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/""> <soap:Body> <GetResources xmlns=""http://www.example.com""> </GetResources> </soap:Body> </soap:Envelope>"; // 执行替换,把返回值赋值给新变量(或者覆盖原变量) string replacedStr = str.Replace("\"", "\"\""); // 验证结果 Console.WriteLine(replacedStr);
这样替换后,原字符串里的每一个"都会被替换成"",完全符合你的需求。
如果你想直接覆盖原字符串,也可以写成:
str = str.Replace("\"", "\"\"");
内容的提问来源于stack exchange,提问作者Lets Do Green
相关产品推荐
相关产品推荐

