String.Replace() in .net 1.1 does NOT work!

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

Guest

Hi, guys,

The following source code did not work:

string pathVal = "2006\";
pathVal.Replace("\\", "/");

I still had the value "2006\", not "2006/", the one I expected.

I then tried the second line as:

pathVal.Replace('\', '/');

still no luck.

Any ideas? Thanks.
 
Andrew said:
The following source code did not work:

string pathVal = "2006\";
pathVal.Replace("\\", "/");

String.Replace returns (a reference to) a _new_ instance containing the new
value. It does not change the value of the current instance, because it
cannot -- strings are immutable (a string's value cannot be changed). Here
is how to achieve what you're attempting:

string pathVal = "2006\";
pathVal = pathVal.Replace("\\", "/");
 
Actually, String.Replace works just fine.

Try:
pathVal = pathVal.Replace("\\", "/")

Pete
 
In addition, I believe that the first line needs to be either:

string pathVal = "2006\\";

//or:

string pathVal = @"2006\";

--Bob
 
Andrew said:
The following source code did not work:

string pathVal = "2006\";
pathVal.Replace("\\", "/");

It worked in that it did what it should have done (nothing) - it just
didn't do what you expected.
I still had the value "2006\", not "2006/", the one I expected.

I then tried the second line as:

pathVal.Replace('\', '/');

still no luck.

Any ideas? Thanks.

Strings are immutable. Calling Replace doesn't change the current
string, it just returns a new one.

Read http://www.pobox.com/~skeet/csharp/strings.html for more about
strings.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top