问题描述
我有一个字符串1112224444",它是一个电话号码.我想在将其存储到文件之前将其格式化为 111-222-4444.它位于数据记录中,我希望能够在没有的情况下执行此操作分配一个新变量.
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.
我在想:
String.Format("{0:###-###-####}", i["MyPhone"].ToString() );
但这似乎并不能解决问题.
but that does not seem to do the trick.
** 更新 **
好的.我选择了这个解决方案
Ok. I went with this solution
Convert.ToInt64(i["Customer Phone"]).ToString("###-###-#### ####")
现在,当扩展名小于 4 位时,它会变得混乱.它将从右侧填写数字.所以
Now its gets messed up when the extension is less than 4 digits. It will fill in the numbers from the right. so
1112224444 333 becomes
11-221-244 3334
有什么想法吗?
推荐答案
请注意,此答案适用于数字数据类型(int、long).如果您以字符串开头,则需要先将其转换为数字.另外,请注意您需要验证初始字符串的长度是否至少为 10 个字符.
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.
来自 好页面 的例子:
String.Format("{0:(###) ###-####}", 8005551212);
This will output "(800) 555-1212".
虽然正则表达式可能会更好,但请记住旧的编程报价:
Although a regex may work even better, keep in mind the old programming quote:
有些人在遇到问题,想我知道,我会用常用表达."现在他们有两个问题.
--Jamie Zawinski,在 comp.lang.emacs 中
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
这篇关于如何在 C# 中将字符串格式化为电话号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!