Nency Nency -4 years ago 103
Android Question

extract the country code from mobile number

I have a list of mobile numbers with country code like "919638095998"number. I have referred the libphonenumber google example also but in that first we need to pass the country 2 digit code, which I don't know initially. So how can I know that the number is from which country?

I have also got one solution as manually extract the code one by one digit from mobile number and then compare with country code. But it is a long task and also it will give me bad performance. Can anyone suggest a proper solution?

Answer Source

There is a list of all the phone numbers available for country codes on Wikipedia. It is here

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

I would create two hashmaps. One with all the four digit codes and one containing both the two and three digit 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. 
     }

In summary. If first digit is 7 Russian. If it is 1 check in the hashmap of four digit codes for the first four numbers if found a four digit code return the corresponding country.if not answer is USA otherwise check first two digits in the hashmap containing the 2 or 3 digits. If found two then return the answer other it is certainly a three digit code and return the corresponding country from the hash.

It will be tedious to make the hashmap but I think an efficient solution.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download