带扩展名的String.Format电话号码

Chi*_*ago 6 c# string

我正在尝试创建一个格式化美国电话号码的功能 - 希望不会遍历每个数字.

全部通过10位数就可以了.但是,当传递超过10位数字时,我希望String.Format方法在右侧附加扩展数字.例如:

当结果中传入的14位数字应该是:(444)555-2222 x8888当结果中传递的12位数应该是:(444)555-2222 x88等.但是我当前尝试得到的是:传入12位数字返回此字符串'() - 949 x555444433'

这是我到目前为止所拥有的.

public static string _FormatPhone(object phonevalue)
{
    Int64 phoneDigits;

    if (Int64.TryParse(phonevalue.ToString(), out phoneDigits))
    {
        string cleanPhoneDigits = phoneDigits.ToString();
        int digitCount = cleanPhoneDigits.Length;

        if (digitCount == 10)
            return String.Format("{0:(###) ###-####}", phoneDigits);
        else if (digitCount > 10)
            return String.Format("{0:(###) ###-#### x#########}", phoneDigits);
        else
            return cleanPhoneDigits;
    }

    return "Format Err#";
}
Run Code Online (Sandbox Code Playgroud)

提前致谢.

Ax.*_*Ax. 2

我认为您必须将phoneDigits 字符串分成前10 位数字和其余数字。

//[snip]
else if (phoneDigits.ToString().Length > 10)
        {
            return String.Format("{0:(###) ###-#### x}{1}", phoneDigits.Substring(0,10), phoneDigits.Substring(10) );
        }
//[snip]
Run Code Online (Sandbox Code Playgroud)