Click here to Skip to main content
15,908,264 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
my string containing "\\\\" and I want to replace it with "\\".
eg: The Original string is "domainName\\\\myname" and resulted string should be "domainName\\myname".

I have tried string.Replace("\\\\", "\\") but this is not working.

How can I find expected resulted string?.

Thanks.
Posted

Try this code:

C#
string s = "\\\\";

string t = s.Replace("\\\\", "\\");


This is working fine. Perhaps, you were not considering the fact that strigns are immutable and thus getting the problem. the string.replace will replace the string and return new string. it will not update the existing string.

Hope it helps and work for you. let me know if my understanding in not correct. i will try to refine my answer.
 
Share this answer
 
VB
Dim str As String = "domainName\\\\myname"
     str = str.Replace("\\\\", "\\")

check this.
 
Share this answer
 
v2
Try using escape sequence ('\')(back slash):
C#
stringOriginal.replace("\\\\\\\\","\\\\");  //if string contains 4 backslashes in actual this will replace with 2


Details here: MSDN: Escape Sequences[^]


But, I believe actual issue would be that you are worried that your string is showing as 'domainName\\\\myname' -> thinking this is wrong you want to correct it. But, this is perfectly fine. You don't need to do any change. '\' needs a escape sequence and CLR automatically applies it at the time of computation. While applying the value it will be 'domainName\\myname' only.
If you want to avoid confusion, define string with @ character.
Like:
C#
string mypath = @"domainName\\myname";
 
Share this answer
 
v3
hi ashriv
the original string = "domainName\\\\myname" itself is equivalent to "domainName\\myname" so i don't think you need to apply replace method to get the desired output. the explanation Sandeep has given is absolutely correct.
 
Share this answer
 
hi
it should work

C#
string s = "\\\\";
string t = s.Replace("\\\\", "\\");
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900