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

时间:2010-08-20 19:35:09

标签: c# asp.net string

我有字符串。

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包含“\”。

4 个答案:

答案 0 :(得分:13)

表达字符串

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

在C#中,您需要转义"字符,因为在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("\"", "");

"\""表示由单个字符"组成的字符串(同样,在此常规字符串文字中转义),""为空字符串。

答案 1 :(得分:3)

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

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

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

E.g。这一行:

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

将打印为:

A string with a " and a \" too.

答案 2 :(得分:2)

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

这很好。

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

答案 3 :(得分:0)

尝试:

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