Reputation: 209
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("-");
}
}
Upvotes: 0
Views: 3086
Reputation:
//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");
}
}
}
Upvotes: 0
Reputation: 13882
String input = "(xxx) xxx-xxxx"
String[] arrFirst = input.split(" ");
String[] arrSecond = arrFirst[1].split("-");
System.out.println(arrFirst[0] + " " +arrSecond[0] + "-" + arrSecond[1]);
Upvotes: 0
Reputation: 1700
String phoneNumber = "(123)456-7890";
String[] parts = phoneNumber.split("\\D+");
for(String part : parts) {
System.out.println(part);
}
Upvotes: 2