TAGS :Viewed: 7 - Published at: a few seconds ago

[ 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 am asked to just use split method of class String. I worked it out in a small programs shown below but is there anyway 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("-");

}

 }

Answer 1


    String phoneNumber = "(123)456-7890";
    String[] parts = phoneNumber.split("\\D+");
    for(String part : parts) {
        System.out.println(part);
    }

Answer 2


String input = "(xxx) xxx-xxxx"
String[] arrFirst = input.split(" ");
String[] arrSecond = arrFirst[1].split("-");

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

Answer 3


//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");
            }


}
}