How to format a string as a telephone number in C#(如何在 C# 中将字符串格式化为电话号码)
问题描述
我有一个字符串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# 中将字符串格式化为电话号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 C# 中将字符串格式化为电话号码
基础教程推荐
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
