简体   繁体   English

如何用双引号替换文件中的字符串

[英]How to Replace String In File With Double Quotes

want to Replace Text in My File strText @Insurer with XYZ output be like this "XYZ" 想要用XYZ输出替换我的文件strText @Insurer中的文本,就像这样的“ XYZ”

till now i do this 直到现在我这样做

strText.Replace("@Insurer",XYZ)

this gives me XYZ but not this "XYZ" 这给了我XYZ但没有这个“ XYZ”

so i did this 所以我做到了

strText.Replace("\"@Insurer\"",XYZ)

but it didn't replace my String with XYZ 但是它没有用XYZ替换我的String

Add double quote around xyz. 在xyz周围添加双引号。 You have to escape the double quotes for that you use escape character ie backslash \\ . 您必须对使用转义字符即反斜杠\\的双引号进行转义。 Also you are not assigning the resultant string back to strText and wont get the changed string. 另外,您没有将结果字符串分配回strText,也不会获得更改后的字符串。

strText = strText.Replace("@Insurer", "\"" + XYZ + "\"");

The second attempt that failed to replace is because you have added double quotes in string that you are trying to find and there are not double quotes in source string. 未能替换的第二次尝试是因为您在要查找的字符串中添加了双引号,并且源字符串中没有双引号。

If you want the text after the replacement to be quoted, then you should put the replacement string in quotes: 如果要在替换的文本加上引号,则应将替换字符串放在引号中:

strText.Replace("@Insurer", "\"" + XYZ + "\"")

Otherwise, you would be searching for the literal string "@Insurer" and just replace it by XYZ . 否则,您将搜索文字字符串"@Insurer"并将其替换为XYZ So if there were quotes (which likely isn't the case, otherwise you wouldn't want to add them), then this would actually remove them. 因此,如果有引号(可能不是这样,否则您不想添加它们),那么实际上将其删除。

Inorder to replace with quotes you can try using backward slash ( "\\" ). 为了用引号替换,您可以尝试使用反斜杠( "\\" )。 The example below shows how to implement. 以下示例显示了如何实现。

public string ReplaceString(string strText)
{
   string replaceWith = "\"XYZ\"";
   string replacedString = strText.Replace("@Insurer", replaceWith);
   return replacedString;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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