Remove formatting from a string: “(123) 456-7890” => “1234567890”?

后端 未结 14 730
一整个雨季
一整个雨季 2021-02-05 01:12

I have a string when a telephone number is inputted - there is a mask so it always looks like \"(123) 456-7890\" - I\'d like to take the formatting out before saving it to the D

14条回答
  •  再見小時候
    2021-02-05 01:14

    Since nobody did a for loop.

    long GetPhoneNumber(string PhoneNumberText)
    {
        // Returns 0 on error
    
        StringBuilder TempPhoneNumber = new StringBuilder(PhoneNumberText.Length);
        for (int i=0;i

    used like this:

    long phoneNumber = GetPhoneNumber("(123) 456-7890"); 
    


    Update
    As pr commented many countries do have zero's in the begining of the number, if you need to support that, then you have to return a string not a long. To change my code to do that do the following:

    1) Change function return type from long to string.
    2) Make the function return null instead of 0 on error
    3) On successfull parse make it return PhoneNumberText

提交回复
热议问题