简体   繁体   中英

validating Phone number in from of (xxx) xxx-xxxx using String method split only

I have to split a phone number in the format of (xxx) xxx-xxxx , I searched around but the solutions I found was about using regular expressions but I was asked to just use split method of class String . I worked it out in a small program shown below but is there a way of doing it with fewer lines of code?

package StringReview;
import java.util.Scanner;

public class StringExercise {

    static Scanner scanner = new Scanner (System.in);
    static String [] number;
    static String array[] ;

    public static void main(String[] args) {

        System.out.println("Enter a phone number: with () and -");
        String phoneNumber = scanner.nextLine();
        array = phoneNumber.split(" ");
        for(String st : array ){
            if(st.contains("-")){
                    number=cut(st);
            }else
                System.out.println(st);             
        }
        for (String str : number){
            System.out.println(str);
        }
    }

    private static String[] cut(String st) {
         return st.split("-");
    }
}
    String phoneNumber = "(123)456-7890";
    String[] parts = phoneNumber.split("\\D+");
    for(String part : parts) {
        System.out.println(part);
    }
String input = "(xxx) xxx-xxxx"
String[] arrFirst = input.split(" ");
String[] arrSecond = arrFirst[1].split("-");

System.out.println(arrFirst[0] + " " +arrSecond[0] + "-" + arrSecond[1]);
//By Benjamin Manford

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class tel {

  public static boolean validatePhone(String phone){
      //the range of numbers is between 9 and 10. you can make it any range you want
            return phone.matches("^[0-9]{9,10}$");
    }

public static void main(String[] args) {


    Scanner input = new Scanner(System.in);
  System.out.print("Enter Phone Number: ");
            String phone = input.nextLine();
            while(validatePhone(phone) != true) {
                    System.out.print("Invalid PhoneNumber!");
                    System.out.println();
                    System.out.print("Enter Phone Number: ");
                    phone = input.nextLine();
                    System.out.println("Correct telephone number");
            }


}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM