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?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Gold
  • 60,526
  • 100
  • 215
  • 315

6 Answers6

105
string r = "123-456-7";
r = r.Replace("-", "");
Sean Bright
  • 118,630
  • 17
  • 138
  • 146
  • 5
    Be careful, it won't work if you use single quotes (indicating a char) => `r.Replace('-', '');` That just bit me in the A** – Kellen Stuart May 15 '19 at 23:33
25

This should do the trick:

String st = "123-456-7".Replace("-","");
Jose Basilio
  • 50,714
  • 13
  • 121
  • 117
23
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.

Community
  • 1
  • 1
Rashmi Pandit
  • 23,230
  • 17
  • 71
  • 111
  • 1
    I do not believe this is true. String.Empty is the constant for "". The compiler points all "" literals to String.Empty. Doesn't matter how many "" literals you have. – AMissico Sep 02 '09 at 06:24
  • 1
    Thanks AMissico ... I just checked the heap for 3.5 framework and you are right, both "" and String.Empty point to the same location. But, for 1.0, there will be space allocated on the heap for "". I've edited the answer accordingly :) – Rashmi Pandit Oct 01 '10 at 03:58
4

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.

abelenky
  • 63,815
  • 23
  • 109
  • 159
2

String.Replace Method (String, String)

in your case it would be

string str = "123-456-7";
string tempstr = str.Replace("-","");
Syed Tayyab Ali
  • 3,643
  • 7
  • 31
  • 36
-1

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.

Darshana
  • 564
  • 1
  • 4
  • 13