views:

115

answers:

4

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

`

+1  A: 

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.

Callum Rogers
+7  A: 

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.

Jon Skeet
Hi, could you please suggest a best way to handle escape chars. There is another post by me
@starz: That depends on what you mean by "handle". You need to be a lot clearer in your questions.
Jon Skeet
I mean i get input strings which might contain \0, \, \\, \t, \a etc. These are input i get from another application.SO when i get such string , My application serializes and then deserializes the string. COnsidering a case of "\0 Mesg" input i get exception while deserailzation. So I want to modify the strin to "\\0Mesg" and then perform a serialization so tht i can avoid a exception while deserialzation.
+3  A: 

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);
CraigTP
A: 
string Method1(string s) 
{
    return s.Replace(@"\", @"\\");
}
Shlomo