c# - String.Format 带分机号的电话号码

标签 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#";
}

提前致谢。

最佳答案

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

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

关于c# - String.Format 带分机号的电话号码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2403767/

相关文章:

c# - 避免子节点出现在父级的同一级或上级

c - 在 C 中比较两个字符串是否相等的最佳方法是什么?

python - 字符串索引超出范围? - Python

c# - 使用 Entity Framework 6 流式传输 varbinary(max) 数据

c# - 为什么等待 ManualResetEvent 的线程即使在调用 Close() 时也会继续等待?

c# - 使用具体类型而不是接口(interface)在性能方面是否更好

MYSQL:以可变的出现次数分割字符串

c# - 鼠标事件处理程序

python - 在 Python 3 中写入文件时,TypeError : a bytes-like object is required, 不是 'str'

c# - 获取字符串第 n 次出现的索引?