转义字符出现在字符串中。

3

我正在使用Visual c# 2010编写一段生成字符串的代码。这个字符串需要包含反斜杠\和引号"。

我尝试过以下几种方法:

string StringOutputVariable;
string StringVariable = "hello world";
StringOutputVariable = "\"C:\\Program Files\\some program\\some program.exe\" " + StringVariable;

并且

string StringOutputVariable;
string StringVariable = "hello world";
StringOutputVariable = @"""C:\Program Files\some program\some program.exe"" " + StringVariable;

然而,它们都将转义字符放入输出字符串中:
\"C:\\Program Files\\some program\\some program.exe\" hello world

\"C:\\Program Files\\some program\\some program.exe\" hello world
我想要的输出是:
"C:\Program Files\some program\some program.exe" hello world
为什么我的代码会将转义字符输出到字符串中?
谢谢 Graham

再检查一遍...........最终你会得到 "C:\Program Files\some program\some program.exe" hello world - andy
2
如果您在调试器中查看,它仍应显示额外的 \。将其打印到控制台以查看您应该看到什么。 - Destrictor
使用调试器的文本可视化器,单击放大镜图标。 - Hans Passant
4个回答

2
StringOutputVariable = "\"" +
        @"C:\Program Files\some program\some program.exe\" + "\" " + StringVariable;

感谢大家的回复,问题已解决。我想我们可以把这归结为“椅子键盘错误”。 - Graham
有些日子就是这样。我想我编辑了两次才把我脑海中的东西呈现在屏幕上。祝你一切顺利! - Vincent James

2

我猜你是在调试器中查看字符串。调试器会将字符串显示为字符串字面量,即带有引号和转义斜杠的形式。字符串与你所期望的一样。

你可以简单地将字符串打印到控制台或将其放在表单中来验证。


谢谢大家的回复,问题已解决。我想我们可以把这归咎于“椅子到键盘”的错误。 - Graham

1

如果字符串是字符串字面量,调试器会显示它们。

可以尝试像这样;

    string StringOutputVariable;
    string StringVariable = "hello world";
    StringOutputVariable = "\"" + @"C:\Program Files\some program\some program.exe\" + "\"" + StringVariable;
    Console.WriteLine(StringOutputVariable);

这里是一个DEMO
输出为:
"C:\Program Files\some program\some program.exe\"hello world

好的...我现在觉得有些羞愧。哈哈。谢谢。 - Graham

1

try this:

string path = @"C:\Program Files\some program\some program.exe";

string result = string.Format("{0}{1}{0} hello world", "\"", path);

// you can check it: MessageBox.Show(result);

谢谢大家的回复,现在问题已经解决了。我认为这是“椅子键盘错误”。 - Graham

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接