在C#字符串中转义双引号

本文关键字:转义 字符串 | 更新日期: 2023-09-27 18:24:59

我正试图在字符串中转义'",如下所示:

text.Replace("''", "''''").Replace("'"", "'''"");

text、的结果

arash "moeen"

结果是

arash '''"moeen'''"

我该怎么解决这个问题?

在C#字符串中转义双引号

只需将@用于逐字逐句的文字字符串。

text.Replace(@"this", @"that");

示例:

text.Replace(@"'", @"''").Replace(@"""", @"'""");

您的作业代码是什么?

应该是

var text = @"arash ""moeen""";

如果我理解正确,首先,text = arash "moeen"不是一个有效的正则字符串文字。我猜想你的琴弦像;

string s = "text = arash '"moeen'"";

打印为

text = arash "moeen" // I think this is your original string.

由于结果是arash '"moeen'",您只需要在类似的字符串中将"替换为'"

string s = "text = arash '"moeen'"";
s = s.Replace("'"", "'''"");

所以你的结果将是arash '"moeen'"

更多信息:Escape Sequences

如果这是一个JSON字符串,我的答案将无效:-p

string text = @"arash ""moeen""";
MessageBox.Show(text.Replace(@"'", @"''").Replace(@"""", @"'"""));

假设您有这样的字符串

string test = "He said to me, '"Hello World'". How are you?";

字符串在任何一种情况下都没有改变——有一个转义的";在里面。这只是告诉C#字符是字符串的一部分而不是字符串终止符的一种方法。

如果要从arash "moeen"获得arash '"moeen'",请执行text.Replace(", '");