String.Replace does not seem to replace brackets with empty string

后端 未结 9 629
鱼传尺愫
鱼传尺愫 2021-01-19 01:26

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

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

Console         


        
相关标签:
9条回答
  • 2021-01-19 01:54

    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.

    0 讨论(0)
  • 2021-01-19 02:06

    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);
    
    0 讨论(0)
  • 2021-01-19 02:12

    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);
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-19 02:12

    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);
    
    0 讨论(0)
  • 2021-01-19 02:12

    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));
    
    0 讨论(0)
提交回复
热议问题