【问题标题】:How to count the number of dashes (-) in a phone number String for input validation?如何计算电话号码字符串中破折号 (-) 的数量以进行输入验证?
【发布时间】:2014-10-10 17:21:01
【问题描述】:

我有一个程序,它读取用户输入的电话号码并返回国家代码(如果存在)、区号(如果存在)和本地 7 位电话号码。
该号码必须输入为 countrycode-area-local。因此,电话号码中最多可以有两个虚线。

例如:
1-800-5555678 有两个破折号(有国家代码和区号)
800-5555678 有一个破折号(只有区号)
5555678 没有破折号(只有本地号码)

因此,可以有 0 个破折号、一个破折号或两个破折号,但不能超过两个。


我想弄清楚的是如何计算字符串中破折号(“-”)的数量,以确保它们的实例不超过两个。如果有,它会打印一个错误。

到目前为止,我有:

if(phoneNumber ///contains more more than two dashed
{
    System.out.println("Error, your input has more than two dashes. Please input using the specified format.");
{
else
{
    //normal operations
}

到目前为止,除了这一部分之外,一切都有效。我不确定使用什么方法来做到这一点。我尝试查看 indexOf,但我很难过。

【问题讨论】:

  • 1-800-555-1212 不是合法电话号码吗?
  • @azurefrog 此程序的要求不允许在 7 位本地电话号码中使用破折号。记得我说的是 countrycode-areacode-local

标签: java validation phone-number


【解决方案1】:

一种方法是将数字解析为字符串,然后在破折号上拆分。如果你得到的新数组的长度大于 3 则报错。

String s = "1-800-5555678";
String parts[] = s.split("-");
if (parts.length > 3) {
    System.out.println("error");
} else {
    // do something
}

samrap 建议的内存效率更高的解决方案是:

String s = "1-800-555-5678";
int dashes = s.split("-").length - 1;
if (dashes > 2) {
    System.out.print("error");
} else {
    // do something
}

【讨论】:

  • 重要的是要记住数组的长度总是比你要分割的字符大一。另外,我建议不要为只需要查找长度的数组分配内存,而是这样做: int dashes = (s.split("-").length) - 1;
【解决方案2】:
String phoneNumber = "1-800-5555678";
int counter = 0;
for( int i=0; i< phoneNumber.length(); i++ ) {
  if( phoneNumber.charAt(i) == '-' ) {
    counter++;
  } 
}

if(counter > 2) ///contains more more than two dashed
{
  System.out.println("Error, your input has more than two dashes. Please input using the     specified format.");
{
else
{
 //normal operations
}

【讨论】:

    【解决方案3】:

    类似的东西。遍历字符串中的字符,看看是否为-

    int nDashes = 0;
    for (int i=0; i<phoneNumber.length(); i++){
        if (phoneNumber.charAt(i)=='-')
            nDashes++;
    }
    if (nDashes>2){
        //do something
    }
    

    【讨论】:

      【解决方案4】:

      正则表达式和replaceAll() 是你的朋友。使用,

      int count=string.replaceAll("\\d","").length();

      这会将所有数字替换为空字符串,因此您将只剩下-s

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-12
        • 2017-10-15
        • 2015-03-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多