By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,647 Members | 1,706 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,647 IT Pros & Developers. It's quick & easy.

string.replace acts unexpectedly in this case

P: n/a
string foo = "v:\\bar.txt";
foo.Replace(@"\\",@"\");
if(foo == "v:\\bar.txt")
MessageBox.Show("Why the heck didn't Replace work? I'm confusied!");
Nov 22 '05 #1
Share this Question
Share on Google+
3 Replies


P: n/a
> string foo = "v:\\bar.txt";
foo.Replace(@"\\",@"\");
if(foo == "v:\\bar.txt")
MessageBox.Show("Why the heck didn't Replace work? I'm confusied!");


Could you please explain what you're expecting the code to replace?

Anders Norås
http://dotnetjunkies.com/weblog/anoras/
Nov 22 '05 #2

P: n/a
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.]

Nov 22 '05 #3

P: n/a
William Sullivan <Wi*************@discussions.microsoft.com> wrote:
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.");
Nov 22 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.