How to replace occurrences of “-” with an empty string?

后端 未结 6 1760
春和景丽
春和景丽 2021-01-17 09:41

I have this string: \"123-456-7\"

I need to get this string: \"1234567\"

How I can replace occurrences of \"-\" with an empty string?

相关标签:
6条回答
  • 2021-01-17 09:51

    Use String.Empty or null instead of "" since "" will create an object in the memory for each occurrences while others will reuse the same object.

    0 讨论(0)
  • 2021-01-17 10:01

    String.Replace Method (String, String)

    in your case it would be

    string str = "123-456-7";
    string tempstr = str.Replace("-","");
    
    0 讨论(0)
  • 2021-01-17 10:03
    string r = "123-456-7";
    r = r.Replace("-", "");
    
    0 讨论(0)
  • 2021-01-17 10:05
    string r = "123-456-7".Replace("-", String.Empty);
    

    For .Net 1.0 String.Empty will not take additional space on the heap but "" requires storage on the heap and its address on the stack resulting in more assembly code. Hence String.Empty is faster than "".

    Also String.Empty mean no typo errors.

    Check the What is the difference between String.Empty and “” link.

    0 讨论(0)
  • 2021-01-17 10:08

    This should do the trick:

    String st = "123-456-7".Replace("-","");
    
    0 讨论(0)
  • To be clear, you want to replace each hyphen (-) with blank/nothing. If you replaced it with backspace, it would erase the character before it!

    That would lead to: 123-456-7 ==> 12457

    Sean Bright has the right answer.

    0 讨论(0)
提交回复
热议问题