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

maf*_*ffo 36 c# trim

我有以下代码

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我已经在我想知道的行中添加了评论网.我想从字符串中删除所有'\'字符.这是正确的方法吗?我不工作.所有\仍然在字符串中.

And*_*huk 97

你可以使用:

line.Replace(@"\", "");
Run Code Online (Sandbox Code Playgroud)

要么

line.Replace(@"\", string.Empty);
Run Code Online (Sandbox Code Playgroud)

  • 那是因为Replace不会更改字符串本身,它会返回更改后的字符串.所以你必须像我的答案那样做,然后写一下`line = line.Rep ...` (4认同)

San*_*sal 8

您可以使用String.Replace基本上删除所有出现的内容

line.Replace(@"\", ""); 
Run Code Online (Sandbox Code Playgroud)


Øyv*_*hen 6

要从字符串中删除所有 '\',只需执行以下操作:

myString = myString.Replace("\\", "");
Run Code Online (Sandbox Code Playgroud)


Fai*_*Dev 5

为什么不简单地这样呢?

resultString = Regex.Replace(subjectString, @"\\", "");
Run Code Online (Sandbox Code Playgroud)

  • 我认为必须为“ \\”或@“ \”不是吗? (2认同)

cra*_*231 5

line = line.Replace("\\", "");
Run Code Online (Sandbox Code Playgroud)


Vea*_*rji 5

尝试更换

string result = line.Replace("\\","");
Run Code Online (Sandbox Code Playgroud)


Olo*_*ulu 5

我已经多次遇到这个问题,令我惊讶的是其中许多都不起作用。

我只需使用 Newtonsoft.Json 反序列化字符串即可得到明文。

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

//the result is: "call 12";
Run Code Online (Sandbox Code Playgroud)