string.replace acts unexpectedly in this case

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

string foo = "v:\\bar.txt";
foo.Replace(@"\\",@"\");
if(foo == "v:\\bar.txt")
MessageBox.Show("Why the heck didn't Replace work? I'm confusied!");
 
string foo does not have the @ in front of it. This means that the \\
is actuall a single \
v:\bar.txt

the call to foo.Replace looks for \\ but doesn't find it, so nothing is
changed.

If you want foo to have \\ then put an @ in front of it or write it as
\\\\


Rob Vretenar [imason inc.]
 
William Sullivan said:
string foo = "v:\\bar.txt";

is equivalent to:

string foo = @"v:\bar.txt";
foo.Replace(@"\\",@"\");

has no effect on 'foo', due to String being immutable.
if(foo == "v:\\bar.txt")

is equivalent to:

if(foo == @"v:\bar.txt")

This should do what you're after:

const string StringWithCuriousDoubleSlash = @"v:\\bar.txt";

string foo = StringWithCuriousDoubleSlash;
foo = foo.Replace(@"\\",@"\");

if (foo != StringWithCuriousDoubleSlash
MessageBox.Show("Success.");
 
Back
Top