views:

48

answers:

2

My program should process an input string. But when "\mesg" is sent in Method1, the else block is executed instead of the if block.

 void Method()
 {
     string str = "\\Mesg";
     str = Method1(str);
     Console.WriteLine(str);
 }

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

The best example is when "\0Mesg" is the input to Method1(). This raises an XML serilaziation exception when I try to deserialze. Just to handle this I want to add another slash, "\0Mesg", before serialzing the string.

How can I make it work as expected?

+2  A: 

Your first conditional will fail, as it's searching for a double slash, while str contains a single slash.

Console.WriteLine(@"\\");  // Double slash
Console.WriteLine("\\");   // Single slash
Console.WriteLine("\\\\"); // Double slash
Console.WriteLine(@"\");   //"// Single slash

str will not produce what you expect it to return, since \ is an escape character.

string str = "\\Mesg";
Console.WriteLine(str); // Returns: "\Mesg"

Try this instead

string myString = "\\Mesg";
Console.WriteLine(myString); // Returns: \Mesg
Console.WriteLine(EscapeSlashes(myString)); //Returns; \\Mesg

public static string EscapeSlashes(string str)
{
    return str.Replace("\\", "\\\\");
}
sshow
NO i would get the string as "\tMesg" or "\0Mesg". THis is input i get. I have to modify the input but caanot ask to send input as "\\\\Mesg"
@starz26: You would have to elaborate. I don't understand what you mean if my answer didn't answer you.
sshow
I meant i cannot ask the sender of input to send data as "\\Mesg". when sender sends "\Mesg" , I have to modify in my application to check, replace such chars with an additonal slash so tht i dont get exception when i serialze the string finally
@starz26: Look at the last code-block to see if I understand you correctly.
sshow
ya but I need to apply this convertion on \0,\t,\b,\n etc.
A: 

Your code is basically correct, you are missing something important for it to work though...

void Method() 
{  
    string str = "\\Mesg"; 
    str = Method1(str);  
    Console.WriteLine(str); 
}

string Method1(string s)
{
    string upadtedString = s;
    if (s.Contains(@"\\")
    {
     //do nothing
    }
    else if(s.Contains(@"\"))
    {
          s = upadtedString.Replace(@"\",@"\\");//Change around here
    }
    return s;
} 

You need to grab what is being replaced. upadtedString.Replace() does NOT modify the string itself, it returns the modified string.

Rangoric