I am not smart
I am not smart

Reputation: 1441

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.

Upvotes: 48

Views: 295413

Answers (10)

Olorunfemi Davis
Olorunfemi Davis

Reputation: 1090

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";

Upvotes: 6

Veaceslav Gaidarji
Veaceslav Gaidarji

Reputation: 4301

Try to replace

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

Upvotes: 5

Vano Maisuradze
Vano Maisuradze

Reputation: 5899

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

Upvotes: 2

Falanwe
Falanwe

Reputation: 4744

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

Upvotes: 2

craig1231
craig1231

Reputation: 3867

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

Upvotes: 8

Sandeep Bansal
Sandeep Bansal

Reputation: 6394

You can use String.Replace which basically removes all occurrences

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

Upvotes: 7

&#216;yvind Br&#229;then
&#216;yvind Br&#229;then

Reputation: 60694

to remove all '\' from a string, simply do the following:

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

Upvotes: 8

Shai
Shai

Reputation: 25619

Try using

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

Upvotes: 4

FailedDev
FailedDev

Reputation: 26930

Why not simply this?

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

Upvotes: 6

Andrey Marchuk
Andrey Marchuk

Reputation: 13483

You could use:

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

or

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

Upvotes: 137

Related Questions