我正在尝试创建一个格式化美国电话号码的函数——希望不会遍历每个数字。
当传入 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/