kAsdh
kAsdh

Reputation: 366

how to change character \ in to -? C#

        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

Answers (3)

Sajeetharan
Sajeetharan

Reputation: 222702

You can also use Regex,

var result = Regex.Replace(@"P\04", @"\\", @"-");
Console.WriteLine(result);

FIDDLE

Upvotes: 1

Akshey Bhat
Akshey Bhat

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

Nisarg Shah
Nisarg Shah

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

Related Questions