Alex Rivera | Logout

How to replace occurrences of "-" with an empty string?

Asked 2009-05-21T20:15:07.240
42

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

I need to get this string: "1234567"

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

Edit
Report

2 Answers

22
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.

answered 2009-05-22T05:06:13.787
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.

answered 2009-05-21T20:21:21.500

Your Answer