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 DB.
How can I do that?
One possibility using linq is:
string justDigits = new string(s.Where(c => char.IsDigit(c)).ToArray());
Adding the cleaner/shorter version thanks to craigmoliver
string justDigits = new string(s.Where(char.IsDigit).ToArray())
You can use a regular expression to remove all non-digit characters:
string phoneNumber = "(123) 456-7890";
phoneNumber = Regex.Replace(phoneNumber, @"[^\d]", "");
Then further on - depending on your requirements - you can either store the number as a string or as an integer. To convert the number to an integer type you will have the following options:
// throws if phoneNumber is null or cannot be parsed
long number = Int64.Parse(phoneNumber, NumberStyles.Integer, CultureInfo.InvariantCulture);
// same as Int64.Parse, but returns 0 if phoneNumber is null
number = Convert.ToInt64(phoneNumber);
// does not throw, but returns true on success
if (Int64.TryParse(phoneNumber, NumberStyles.Integer, 
       CultureInfo.InvariantCulture, out number))
{
    // parse was successful
}
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<PhoneNumberText.Length;i++)
    {
        if (!char.IsDigit(PhoneNumberText[i]))
            continue;
        TempPhoneNumber.Append(PhoneNumberText[i]);
    }
    PhoneNumberText = TempPhoneNumber.ToString();
    if (PhoneNumberText.Length == 0)
        return 0;// No point trying to parse nothing
    long PhoneNumber = 0;
    if(!long.TryParse(PhoneNumberText,out PhoneNumber))
        return 0; // Failed to parse string
    return PhoneNumber;
}
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 
You can make it work for that number with the addition of a simple regex replacement, but I'd look out for higher initial digits.  For example, (876) 543-2019 will overflow an integer variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With