如何在 C# 中将字符串格式化为电话号码

How to format a string as a telephone number in C#(如何在 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# 中将字符串格式化为电话号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)