Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace two slash into one slash?

Tags:

c#

.net

We have the following code:

string str="\\u5b89\u5fbd\\";

We need output in the format:

"\u5b89\u5fbd\"

We have tried this code:

str.Replace("\\",@"\")

Its not working.

like image 725
PrateekSaluja Avatar asked Mar 15 '12 11:03

PrateekSaluja


2 Answers

Try this

string str = "\\u5b89\u5fbd\\";
str = str.Replace(@"\\", @"\");

\ is a reserved sign. \\ escapes it and results in \
Adding @ at the start of a string tell the compiler to use the string as is and not to escape characters.

So use either "\\\\" or @"\\"

EDIT

\\u5b89\u5fbd\\ actually does not have two \ together. \ is just escaped.
The string results in \u5b89徽\. And in that string you can't replace \\ because there is only one \ together.

like image 106
juergen d Avatar answered Sep 19 '22 06:09

juergen d


Have you tried this?

str.Replace("\\\\","\\");

Your example accomplish nothing. "\\" is an escaped version of \, and @"\" is another version of writing \. So your example replaces \ with \

EDIT Now I understand your problem. What you want can't actually be done, since that would cause the string to end with a single \, and that will not be allowed. \ denotes a start of a escape sequence, and needs something after it.

I think there are no good option here, since in your case \u5b89 is not a string, but an escape sequence for one specific character.

str.Replace("\\u5b89","\u5b89");

This works for your current example, but will only work with this one specific character, so I guess it wont help you much. The \ at the end you cannot replace with \, but I can't see why you need the string to end with this char either.

Your best bet is to make sure that the \ does not occur at the start of the string in the first place, instead of trying to get rid of it afterwards.

like image 33
Øyvind Bråthen Avatar answered Sep 23 '22 06:09

Øyvind Bråthen