从C#字符串中删除 '\' 字符

47

我有以下代码

string line = ""; 

while ((line = stringReader.ReadLine()) != null)
{
    // split the lines
    for (int c = 0; c < line.Length; c++)
    {
        if ( line[c] == ',' && line[c - 1] == '"' && line[c + 1] == '"')
        {
            line.Trim(new char[] {'\\'}); // <------
            lineBreakOne = line.Substring(1, c  - 2);
            lineBreakTwo = line.Substring(c + 2, line.Length - 2);
        }
    }
}

我在想要移除字符串中所有的 '\' 字符,为此已经在这一行添加了注释。这是正确的做法吗?但是它没有生效,所有的 '\' 仍然存在于字符串中。


1
Trim(new char[] {'\\'}) 将从开头或结尾删除所有 \ 字符。它会将它们“修剪”掉。正如 @user978511 所述,您可以使用 Replace("\\", "")。 (FYI,他使用 @ 字符表示“按照字面意思处理此字符串,而不应用转义规则”) - JohnL
以下的解决方案对我都不起作用... - ccoutinho
Regex.Unescape() - Alexander
10个回答

134

你可以使用:

line.Replace(@"\", "");
或者
line.Replace(@"\", string.Empty);

9
这是因为Replace不会改变原始字符串本身,它会返回修改后的字符串。所以你需要像我的回答那样写line = line.Rep... - Øyvind Bråthen
1
这些不是斜杠。这些是转义字符。它们在这里用于转义引号。考虑使用单引号而不是双引号。那样的话,你就不需要斜杠了。 - Andrey Marchuk
1
@PoiXen - 在你所发布的字符串中,\" 是一个转义序列,它让 " 出现在字符串中。其中没有反斜杠字符。 - Oded
为了获得最优解,请参考以下链接:https://dev59.com/73NA5IYBdhLWcg3wBpDs - Gerhard Powell
无法处理此 ""something://player.vimeo.com/video/27735162""。 - reza.cse08
1
@reza.cse08 因为你的字符串中没有 \,所以你有引号,这个引号是用 \ 转义的 - 就像 "。 - Andrey Marchuk

8
line = line.Replace("\\", "");

7
要从字符串中删除所有“\”,只需执行以下操作:
myString = myString.Replace("\\", "");

7
你可以使用 String.Replace,它可以基本上删除所有出现的内容。
line.Replace(@"\", ""); 

6
为什么不直接这样做呢?
resultString = Regex.Replace(subjectString, @"\\", "");

2
我认为应该是 "\" 或者 @"",不是吗? - Bali C
1
@BaliC 实际上不是这样的。如果只有一个 "",那么你会得到解析 "" - Illegal \ at end of pattern 的错误。 .NET 3.5 - FailedDev

5

我曾多次遇到这个问题,令我惊讶的是许多解决方法都无效。

我只需使用Newtonsoft.Json反序列化字符串,就可以获得明文。

string rough = "\"call 12\"";
rough = JsonConvert.DeserializeObject<string>(rough);

//the result is: "call 12";

5

尝试替换

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

4

尝试使用

String sOld = ...;
String sNew =     sOld.Replace("\\", String.Empty);

2

Trim 只能删除字符串开头和结尾的字符,这就是为什么你的代码不能正常工作。你应该使用 Replace 代替:

line.Replace(@"\", string.Empty);

2
         while ((line = stringReader.ReadLine()) != null)
         {
             // split the lines
             for (int c = 0; c < line.Length; c++)
             {
                 line = line.Replace("\\", "");
                 lineBreakOne = line.Substring(1, c - 2);
                 lineBreakTwo = line.Substring(c + 2, line.Length - 2);
             }
         }

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