views:

754

answers:

9

Hello,

The following bit of C# code does not seem to do anything:

String str = "{3}";
str.Replace("{", String.Empty);
str.Replace("}", String.Empty);

Console.WriteLine(str);

This ends up spitting out: {3}. I have no idea why this is. I do this sort of thing in Java all the time. Is there some nuance of .NET string handling that eludes me?

Brian

+16  A: 

The String class is immutable; str.Replace will not alter str, it will return a new string with the result. Try this one instead:

String str = "{3}";
str = str.Replace("{", String.Empty);
str = str.Replace("}", String.Empty);

Console.WriteLine(str);
Fredrik Mörk
+5  A: 

I guess you'll have to do

String str = "{3}";
str = str.Replace("{", String.Empty);
str = str.Replace("}", String.Empty);

Console.WriteLine(str);

Look at the String.Replace reference:

Return Value Type: System.String

A String equivalent to this instance but with all instances of oldValue replaced with newValue.

schnaader
+5  A: 

The Replace function returns the modified string, so you have to assign it back to your str variable.

String str = "{3}";
str = str.Replace("{", String.Empty);
str = str.Replace("}", String.Empty);

Console.WriteLine(str);
Dave Cluderay
+6  A: 

Str.Replace returns a new string. So, you need to use it as follows:

String str = "{3}";
str = str.Replace("{", String.Empty);
str = str.Replace("}", String.Empty);
Jose Basilio
+6  A: 

Replace actually does not modify the string instance on which you call it. It just returns a modified copy instead.

Try this one:

String str = "{3}";
str = str.Replace("{", String.Empty);
str = str.Replace("}", String.Empty);

Console.WriteLine(str);
User
+7  A: 

String is immutable; you can't change an instance of a string. Your two Replace() calls do nothing to the original string; they return a modified string. You want this instead:

String str = "{3}";
str = str.Replace("{", String.Empty);
str = str.Replace("}", String.Empty);

Console.WriteLine(str);

It works this way in Java as well.

Michael Petrotta
+4  A: 

I believe that str.Replace returns a value which you must assign to your variable. So you will need to do something like:

String str = "{3}";
str = str.Replace("{", String.Empty);
str = str.Replace("}", String.Empty);

Console.WriteLine(str);
Ender
+3  A: 

The Replace method returns a string with the replacement. What I think you're looking for is this:

str = str.Replace("{", string.Empty);
str = str.Replace("}", string.Empty);

Console.WriteLine(str);
Alexander Kahoun
+2  A: 

besides all of the suggestions so far - you could also accomplish this without changing the value of the original string by using the replace functions inline in the output...

String str = "{3}";

Console.WriteLine(str.Replace("{", String.Empty).Replace("}", String.Empty));
Scott Ivey