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

后端 未结 14 723
一整个雨季
一整个雨季 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:35
    public static string DigitsOnly(this string phoneNumber)
    {
        return new string(
            new[]
                {
                 // phoneNumber[0],     (
                    phoneNumber[1],  // 6
                    phoneNumber[2],  // 1
                    phoneNumber[3],  // 7
                 // phoneNumber[4],     )
                 // phoneNumber[5],   
                    phoneNumber[6],  // 8
                    phoneNumber[7],  // 6
                    phoneNumber[8],  // 7
                 // phoneNumber[9],     -
                    phoneNumber[10], // 5
                    phoneNumber[11], // 3
                    phoneNumber[12], // 0
                    phoneNumber[13]  // 9
                });
    }
    
    0 讨论(0)
  • 2021-02-05 01:36

    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())
    
    0 讨论(0)
提交回复
热议问题