Serializing a string with backslash
My program should process an input string. But when "\mesg" is sent in Method1, the els开发者_StackOverflow中文版e 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?
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("\\", "\\\\");
}
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.
精彩评论