replace \\ with \ in c#

  • Thread starter Thread starter mp
  • Start date Start date
M

mp

when I write this in c# :
strFileToLoad = strFileToLoad.Substring(0, 2) +
strFileToLoad.Substring(2).Replace("\\", "\");

it doesnt like the last "\", and I want to replace \\ with \

what should I do?

Thanks
 
mp,

The \ character is an escape character. You either have to double them
up, or use a string literal:

// Using string literals.
strFileToLoad = strFileToLoad.Substring(0, 2) +
strFileToLoad.Substring(2).Replace(@"\\", @"\");

// Using escape sequences.
strFileToLoad = strFileToLoad.Substring(0, 2) +
strFileToLoad.Substring(2).Replace("\\\\", "\\");

Hope this helps.
 
mp said:
when I write this in c# :
strFileToLoad = strFileToLoad.Substring(0, 2) +
strFileToLoad.Substring(2).Replace("\\", "\");

it doesnt like the last "\", and I want to replace \\ with \

what should I do?

mp,

In C# string literals, the \ character tells the C# compiler to treat
the following character in a special way. E.g. \n is interpreted
as a newline character, \t as a tab, etc.

http://msdn.microsoft.com/library/d...en-us/csspec/html/vclrfcsharpspec_2_4_4_5.asp

or

http://tinyurl.com/4zncw


To prevent this from happening, precede the string with the @ symbol.

strFileToLoad = strFileToLoad.Substring(0, 2) +
strFileToLoad.Substring(2).Replace(@"\\", @"\");
 
hi mp!

to get one "\" in a string you need to double them, ie "\\"
strFileToLoad = strFileToLoad.Substring(0, 2) +
strFileToLoad.Substring(2).Replace("\\\\", "\\");

or you can place a @ symbol in front of the string literal so the system
parses it like a good ol' VB string (no escape/specials characters) :
 
Try using verbatim string literals:

strFileToLoad.Substring(2).Replace(@"\\", @"\");

Regards,
Joakim
 
Back
Top