myWorld
myWorld

Reputation: 49

Replacing \ with \\

I have a string. I want to search for a single slash and then replace "\" (single slash) with a "\" (double slash).

string Method1(string s) 
{
     string upadtedString = s;
     if (s.Contains("\\"))
     {
      //do nothing
     }
     else if(s.Contains("\"))
     {
          string s1 = "\";
          string s2 = "\\";
          upadtedString.Replace(s1,s2);
          s = upadtedString;
     }
     return s;
 } 

`

Upvotes: 1

Views: 2054

Answers (4)

Shlomo
Shlomo

Reputation: 14350

string Method1(string s) 
{
    return s.Replace(@"\", @"\\");
}

Upvotes: 0

CraigTP
CraigTP

Reputation: 44909

You need to use the @ character in front of your string literals to ensure that they're taken as verbatim strings and your slashes not interpreted as escape characters. You can also "escape" the \ character but using an additional \.

For example:

string s1 = @"\";
string s2 = @"\\";
string s3 = updatedString.Replace(s1,s2);

or

string s1 = "\\";
string s2 = "\\\\";
string s3 = updatedString.Replace(s1,s2);

Upvotes: 3

Callum Rogers
Callum Rogers

Reputation: 15829

You need to either escape your backslashes, or use string literals, so try:

string Method1(string s) 
{
    return s.Replace(@"\", @"\\");
}

or

string Method1(string s) 
{
    return s.Replace("\\", "\\\\");
}

There are also other problems with your code - you can initialise variables when you declare them:

string upadtedString = s;

The Replace method will not change anything if there are no \ to be found, therefore there is no need for if (s.Contains("\")).

Strings are immutable (Do not change) so you need to use string replaced = original.Replace(...); rather than expecting orginal.Replace(...) to change original in place.

You can declare strings directly into the method call rather than using s1 and s2.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500385

You need to escape backslashes or use a verbatim string literal, and also understand that strings are immutable - Replace doesn't change the existing string, it returns a new string:

// Escaping with an extra backslash
updatedString = s.Replace("\\", "\\\\");

// Using a verbatim string literal
updatedString = s.Replace(@"\", @"\\");

For more information on escaping and verbatim string literals, see my strings article.

Upvotes: 7

Related Questions