tags:

views:

799

answers:

7

Hi

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

I need to get this string: "1234567"

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

Thanks in advance

+34  A: 
string r = "123-456-7";
r = r.Replace("-", "");
Sean Bright
Beat me by 17.3745853 secs +1
Jose Basilio
Actually 36 seconds, from where I'm standing. ;)
Michael Myers
So Simple ????????????????????
Gold
Yes. Unless I didn't understand your question.
Sean Bright
+15  A: 

This should do the trick:

String st = "123-456-7".Replace("-","");
Jose Basilio
All in one line. Cool +1
ichiban
+5  A: 

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
A: 

String.Replace Method (String, String)

in your case it would be

string str = "123-456-7";
string tempstr = str.Replace("-","\b");
Syed Tayyab Ali
A: 

StringBuilder strB = new StringBuilder("123-456-7"); strB.Replace("-", string.Empty); string result = strB.ToString();

Barry Hurt
+6  A: 
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 Sting.Empty is faster than "".

Also String.Empty mean no typo errors.

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

Rashmi Pandit
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
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
A: 

Any of the above method I guess is fine whereas if you are into some complex operation better think of regex it is really great.

Pranali Desai