String.Replace doesn't seem to replace brackets with an empty string

The following bit of C # code does nothing:

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

Console.WriteLine(str);

As a result, it spits out: {3}. I have no idea why this is. I do this all the time in Java. Is there any nuance in .NET string processing that eludes me?

Brian

+5
source share
9 answers

Class String immutable ; str.Replacewill not change str, it will return a new line with the result. Try instead:

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

Console.WriteLine(str);
+18
source

The string is immutable; You cannot change an instance of a string. Your two calls to Replace () do nothing with the original string; they return the modified string. Instead, you want:

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

Console.WriteLine(str);

It also works in Java.

+8

, . .

:

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

Console.WriteLine(str);
+7

Str.Replace . , :

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

,

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

Console.WriteLine(str);

String.Replace:

: System.String

, , oldValue newValue.

+5

Replace , str.

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

Console.WriteLine(str);
+5

, str.Replace , . - :

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

Console.WriteLine(str);
+4

The method Replacereturns a replacement string. I think you are looking for:

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

Console.WriteLine(str);
+3
source

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

String str = "{3}";

Console.WriteLine(str.Replace("{", String.Empty).Replace("}", String.Empty));
+3
source

All Articles