从手机号码中提取国家/地区代码

Nen*_*ncy 6 java android contacts

我有一个国家代码的手机号码列表,如"919638095998"号码.我已经提到了libphonenumber谷歌的例子,但首先我们需要传递国家2位数的代码,我最初不知道.那么我怎么知道这个数字来自哪个国家?

我还有一个解决方案,从手机号码手动提取代码,然后与国家代码进行比较.但这是一项长期任务,也会给我带来糟糕的表现.谁能提出正确的解决方案?

Joã*_*ves 8

libphonenumber为您做到这一点。您所要做的就是+在电话号码前添加符号,并在解析电话号码时省略国家/地区代码。

String numberStr = "+919638095998";
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
try {
    Phonenumber.PhoneNumber numberProto = phoneUtil.parse(numberStr, "");

    System.out.println("Country code: " + numberProto.getCountryCode());
    //This prints "Country code: 91"
} catch (NumberParseException e) {
    System.err.println("NumberParseException was thrown: " + e.toString());
}
Run Code Online (Sandbox Code Playgroud)


Ken*_*Man 5

Wikipedia上有可用于国家代码的所有电话号码的列表。是这里

http://en.wikipedia.org/wiki/List_of_country_calling_codes

我将创建两个哈希图。一种带有所有四位数代码,另一种同时包含两位和三位数代码。

Hashmap fourdigitcodes;

//check if first digit is 7
if(firstdigit==7)
  //country definitely russia
else
   if country code begins with 1.
     Check the first four digits are in the hashmap with four digit codes and return the value 
     if no value is found then answer is certainly usa.
otherwise
     String country="";
     HashMap<String,String> ccode = new HashMap<String,String>();
     ccode.put("353","Ireland");//List all country codes
     ccode.put("49","Germany");
     String value = ccode.get("49");//See if I have a value for the first 2 digits
     if(value != null){
      country = value; //If I found a country for the first two digits we are done as the              first two digits of the country code consisting of two digits cannot be in a country code with 3
     }else{
      the country is certainly 3 digit. return the first three digits by entering the first 3 digits as the key of the hashmap countaining the first three digits. 
     }
Run Code Online (Sandbox Code Playgroud)

综上所述。如果第一位数字是7俄语。如果为1,则在四位数代码的哈希图中检查前四个数字,如果发现四位数代码则返回相应的国家/地区;如果否,则返回美国,否则检查哈希图中包含前两位或三位数的前两位数字。如果找到两个,则返回其他答案,这肯定是一个三位数代码,然后从哈希中返回相应的国家/地区。

制作哈希图将很繁琐,但我认为这是一种有效的解决方案。