Reputation: 366
string s = "P\04";
string z = s.Replace('\\', '-');
Console.WriteLine(z);
I need to replace '\' character in to '-' character in a string. I tried several ways to replace, couldn't able to do for '\' character only. Please any one suggest a way to do this
Upvotes: 0
Views: 117
Reputation: 222702
You can also use Regex,
var result = Regex.Replace(@"P\04", @"\\", @"-");
Console.WriteLine(result);
Upvotes: 1
Reputation: 8545
string s = @"P\04";
string z = s.Replace('\\', '-');
Console.WriteLine(z);
Add @ at the before value of string s to make it a verbatim. That way '\' is treated as is. Otherwise \0 are treated as one character to make a different character.
Upvotes: 2
Reputation: 14561
Your code to replace the \
is fine. The problem is with your input string, where the \
escapes the 0
. It would work if you had this:
string s = "P\\04";
string z = s.Replace('\\', '-');
Console.WriteLine(z);
The output is P-04
assuming that's what you expect.
Upvotes: 4