用java分割美国电话号码?

时间:2012-11-29 06:00:47

标签: java regex

我有如下要求。我有美国电话号码(10)数字,我需要从中提取areacode,前缀和数字。

Ex: 1234567890
it should take 1234567890 and it should return 3 strings as below:

123
456
7890

我该怎么做?

谢谢!

4 个答案:

答案 0 :(得分:4)

String areaCode = number.substring(0,3);
String prefix = number.substring(3,6);
String rest = number.substring(6);

希望有所帮助!

答案 1 :(得分:3)

import java.util.Scanner;

Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter the 10-digit phone number, e.g. 1234567890");
String phoneNum = Integer.toString(keyboard.nextInt()); 

String first = phoneNum.substring(0,3);
String second = phoneNum.substring(3,6);
String third = phoneNum.substring(6);

System.out.println(first);
System.out.println(second);
System.out.println(third);

Run Output:

A prompt appears asking for this:
Please enter the 10-digit phone number, e.g. 1234567890

You enter (for example) 1234567890.

Method takes the substrings, and prints them on its own separate line.
Final Output: 

123
456
7890

希望有所帮助!

答案 2 :(得分:1)

String str =“1234567890”;

    System.out.println(str.substring(0,3));
    System.out.println(str.substring(3,6));
    System.out.println(str.substring(6));

答案 3 :(得分:1)

您也可以尝试这种模式:

(\d){3}(\d){3}(\d){4}$