如何在C#中将字符串格式化为电话号码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/188510/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to format a string as a telephone number in C#
提问by Brian G
I have a string "1112224444' it is a telephone number. I want to format as 111-222-4444 before I store it in a file. It is on a datarecord and I would prefer to be able to do this without assigning a new variable.
我有一个字符串“1112224444”,它是一个电话号码。我想在将其存储在文件中之前将其格式化为 111-222-4444。它位于数据记录上,我希望能够在不分配新的情况下执行此操作多变的。
I was thinking:
我刚在想:
String.Format("{0:###-###-####}", i["MyPhone"].ToString() );
but that does not seem to do the trick.
但这似乎不起作用。
** UPDATE **
** 更新 **
Ok. I went with this solution
好的。我采用了这个解决方案
Convert.ToInt64(i["Customer Phone"]).ToString("###-###-#### ####")
Now its gets messed up when the extension is less than 4 digits. It will fill in the numbers from the right. so
现在,当扩展名少于 4 位时,它会变得一团糟。它将从右侧填充数字。所以
1112224444 333 becomes
11-221-244 3334
Any ideas?
有任何想法吗?
回答by mattruma
As far as I know you can't do this with string.Format ... you would have to handle this yourself. You could just strip out all non-numeric characters and then do something like:
据我所知,你不能用 string.Format 做到这一点......你必须自己处理。您可以删除所有非数字字符,然后执行以下操作:
string.Format("({0}) {1}-{2}",
phoneNumber.Substring(0, 3),
phoneNumber.Substring(3, 3),
phoneNumber.Substring(6));
This assumes the data has been entered correctly, which you could use regular expressions to validate.
这假设数据已正确输入,您可以使用正则表达式进行验证。
回答by Jon Skeet
You'll need to break it into substrings. While you coulddo that without any extra variables, it wouldn't be particularly nice. Here's one potential solution:
您需要将其分解为子字符串。虽然你可以在没有任何额外变量的情况下做到这一点,但它不会特别好。这是一种潜在的解决方案:
string phone = i["MyPhone"].ToString();
string area = phone.Substring(0, 3);
string major = phone.Substring(3, 3);
string minor = phone.Substring(6);
string formatted = string.Format("{0}-{1}-{2}", area, major, minor);
回答by Joel Coehoorn
If you can get i["MyPhone"]
as a long
, you can use the long.ToString()
method to format it:
如果可以获取i["MyPhone"]
为long
,则可以使用该long.ToString()
方法对其进行格式化:
Convert.ToLong(i["MyPhone"]).ToString("###-###-####");
See the MSDN page on Numeric Format Strings.
请参阅有关数字格式字符串的 MSDN 页面。
Be careful to use long rather than int: int could overflow.
小心使用 long 而不是 int:int 可能会溢出。
回答by Ryan Duffield
I prefer to use regular expressions:
我更喜欢使用正则表达式:
Regex.Replace("1112224444", @"(\d{3})(\d{3})(\d{4})", "--");
回答by Sean
Please note, this answer works with numeric data types (int, long). If you are starting with a string, you'll need to convert it to a number first. Also, please take into account that you'll need to validate that the initial string is at least 10 characters in length.
请注意,此答案适用于数字数据类型(int、long)。如果您以字符串开头,则需要先将其转换为数字。此外,请注意您需要验证初始字符串的长度是否至少为 10 个字符。
From a good pagefull of examples:
从一个充满示例的好页面:
String.Format("{0:(###) ###-####}", 8005551212);
This will output "(800) 555-1212".
Although a regex may work even better, keep in mind the old programming quote:
尽管正则表达式可能效果更好,但请记住旧的编程引用:
Some people, when confronted with a problem, think “I know, I'll use regular expressions.” Now they have two problems.
--Jamie Zawinski, in comp.lang.emacs
有些人在遇到问题时会想“我知道,我会使用正则表达式”。现在他们有两个问题。
--Jamie Zawinski,在 comp.lang.emacs
回答by Sean
Use Match in Regex to split, then output formatted string with match.groups
在 Regex 中使用 Match 进行拆分,然后使用 match.groups 输出格式化的字符串
Regex regex = new Regex(@"(?<first3chr>\d{3})(?<next3chr>\d{3})(?<next4chr>\d{4})");
Match match = regex.Match(phone);
if (match.Success) return "(" + match.Groups["first3chr"].ToString() + ")" + " " +
match.Groups["next3chr"].ToString() + "-" + match.Groups["next4chr"].ToString();
回答by Sean
Function FormatPhoneNumber(ByVal myNumber As String)
Dim mynewNumber As String
mynewNumber = ""
myNumber = myNumber.Replace("(", "").Replace(")", "").Replace("-", "")
If myNumber.Length < 10 Then
mynewNumber = myNumber
ElseIf myNumber.Length = 10 Then
mynewNumber = "(" & myNumber.Substring(0, 3) & ") " &
myNumber.Substring(3, 3) & "-" & myNumber.Substring(6, 3)
ElseIf myNumber.Length > 10 Then
mynewNumber = "(" & myNumber.Substring(0, 3) & ") " &
myNumber.Substring(3, 3) & "-" & myNumber.Substring(6, 3) & " " &
myNumber.Substring(10)
End If
Return mynewNumber
End Function
回答by Mak
public string phoneformat(string phnumber)
{
String phone=phnumber;
string countrycode = phone.Substring(0, 3);
string Areacode = phone.Substring(3, 3);
string number = phone.Substring(6,phone.Length);
phnumber="("+countrycode+")" +Areacode+"-" +number ;
return phnumber;
}
Output will be :001-568-895623
输出将是:001-568-895623
回答by Larry Smithmier
To take care of your extension issue, how about:
要解决您的扩展问题,请执行以下操作:
string formatString = "###-###-#### ####";
returnValue = Convert.ToInt64(phoneNumber)
.ToString(formatString.Substring(0,phoneNumber.Length+3))
.Trim();
回答by Vivek Shenoy
This should work:
这应该有效:
String.Format("{0:(###)###-####}", Convert.ToInt64("1112224444"));
OR in your case:
或在您的情况下:
String.Format("{0:###-###-####}", Convert.ToInt64("1112224444"));