简体   繁体   中英

Remove '\' char from string c#

I have the following code

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);
        }
    }
}

I have added a comment net to the line I am wondering about. I want to remove all '\\' chars from the string. Is this the correct way to to this? I doesnt work. All \\ are still in the string.

You could use:

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

or

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

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

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

为什么不简单呢?

resultString = Regex.Replace(subjectString, @"\\", "");

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

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

Try using

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

尝试更换

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

I have faced this issue so many times and I was surprised that many of these don't work.

I simply deserialize the string with Newtonsoft.Json and I get cleartext.

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

//the result is: "call 12";

Trim only removes characters at the beginning and the end of the string, that's why your code doesn't quite work. You should use Replace instead:

line.Replace(@"\", string.Empty);
         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);
             }
         }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM