字符串双引号替换为空的c#

问题描述:

我有字符串。字符串双引号替换为空的c#

There are no items to show in this view of the "Personal Documents" 

然后分配到字符串str变量

string str ="There are no items to show in this view 
of the \"Personal Documents\" library" 

现在打算替换 “\”,并使其实际字符串为str对象。我试过以下,但没有工作

str = str.Replace(@"\",string.Empty); 

我希望的STR值应该是

string str ="There are no items to show in this view 
of the "Personal Documents" library" 

我需要找到这个字符串在另一个字符串。在搜索该字符串时。我找不到,因为str包含“\”。

+10

你一定要明白的是,''\\人物实际上不是字符串的一部分,但仅转义字符处理引号? – 2010-08-20 19:38:40

如果我理解你的问题正确的话,你要替换的字符串常量"\"。这不是必需的,它由编译器为您完成。

,你必须把\(转义序列)的原因"之前是告诉你要在字符串中包含的",不终止字符串常量,编译器。

当存储在内存中时,转义字符已被删除,并且当使用该字符串(例如,在屏幕上打印)时,它不会显示。

E.g.行:

Console.WriteLine("A string with a \" and a \\\" too."); 

将打印为:

A string with a " and a \" too. 

string str ="There are no items to show in this view of the \"Personal Documents\" library"; 

这工作正常。

启动一个控制台应用程序,并写入str与控制台Console.Write作为一个信心提升。

为了表达在C#中的字符串

 
There are no items to show in this view of the "Personal Documents" 

,你需要躲避"字符,因为"在C#中用于包围字符串文字。

有两种选择:

  • 规则字符串

    string str = "There are no items to show in this view of the \"Personal Documents\""; 
                      ↑     ↑ 
    
  • 和逐字字符串

    string str = @"There are no items to show in this view of the ""Personal Documents"""; 
          ↑            ↑     ↑ 
    

注意,在这两种情况下"字符被转义。

在这两种情况下,str变量都保持相同的字符串。例如,

Console.WriteLine(str); 

打印

 
There are no items to show in this view of the "Personal Documents" 

参见:Strings (MSDN)


编辑:如果你有串

 
There are no items to show in this view of the "Personal Documents" 

,并希望把在成

 
There are no items to show in this view of the Personal Documents 

可以使用String.Replace Method这样的:

string str = "There are no items to show in this view of the \"Personal Documents\""; 

string result = str.Replace("\"", ""); 

"\""表示由单个字符"(同样,在这个常规逃串字符串文字)和""是空字符串。

尝试:

string str = @"There are no items to show in this view of the ""Personal Documents"" library" 
+0

dtb打我吧=) – AndHeCodedIt 2010-08-20 19:44:39

+1

上面的代码是不正确的。编译器将返回一个错误。即使使用逐字字符串文字(即用带@字符的引号字符串前缀),引号字符仍需要用额外的引号进行转义。 – 2010-08-20 19:47:57

+0

我注意到了这一点,并在我发布答案后立即修复了它。 – AndHeCodedIt 2010-08-20 19:52:43