Java:将字符串格式化为电话号码 [英] Java: Format a string as a telephone number

查看:336
本文介绍了Java:将字符串格式化为电话号码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个未格式化的电话号码字符串(5551234567)。我想在ui中格式化此字符串以用于显示目的。格式后数字应如下所示:

I have an unformatted telephone number string ("5551234567"). I would like to format this string for display purposes in the ui. The number should look like this after format:

(555)123-4567

(555) 123-4567

叹气...... 。

我试图找到一种考虑美国和国际电话号码的通用方法。我来自JDK中的MaskFormatter,但发现Javadoc中存在一个错误。这引导我在这里问我的问题。我希望有一个解决方案,我可以输入一个掩码,然后输入实际的字符串。对于国际/美国号码,输出将相应地格式化,或者如果指定了错误的字符数,则将显示一些默认字符来代替丢失的字符........

I was trying to find a generic way that would take into account both US and international phone numbers. I came accross the MaskFormatter in the JDK but discovered that there is a bug in the Javadoc. Which lead me to asking my question here. I was hoping for a solution where I could input a mask then the actual string. The output would be formatted accordingly for international/US numbers or if the wrong number of characters were specified, some default character would be displayed in place of the missing characters........

http://www.java.net/node/660119

推荐答案

String.format("(%s) %s-%s", number.substring(0, 3), number.substring(3, 6), 
          number.substring(6, 10));

这篇关于Java:将字符串格式化为电话号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆