java 从手机号码中提取国家代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12259347/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 08:12:47  来源:igfitidea点击:

extract the country code from mobile number

javaandroidcontacts

提问by Nency

I have a list of mobile numbers with country code like "919638095998"number. I have referred the libphonenumber google examplealso 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?

我有一个带有国家代码的手机号码列表,例如“919638095998”号码。我也提到了libphonenumber google 示例,但首先我们需要传递国家/地区 2 位代码,我最初不知道。那么我怎么知道这个号码来自哪个国家呢?

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?

我也有一个解决方案,即从手机号码中手动提取一个数字的代码,然后与国家/地区代码进行比较。但这是一项漫长的任务,也会给我带来糟糕的表现。任何人都可以提出适当的解决方案吗?

采纳答案by KennyBartMan

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

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.

总之。如果第一个数字是 7 俄语。如果是 1 检查前四个数字的四位代码的哈希映射,如果找到四位代码返回相应的国家。如果不是,则回答美国,否则检查哈希映射中包含 2 或 3 位数字的前两位数字。如果找到两个则返回答案,其他肯定是一个三位数的代码,并从散列中返回相应的国家/地区。

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

制作哈希图会很乏味,但我认为这是一个有效的解决方案。

回答by Jo?o Neves

libphonenumberdoes that for you. All you have to do is add the +sign before your phone number and omit the country code when parsing the phone number.

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());
}

回答by Willem

if it's not late

如果不晚

Just looking for this I found a Java and Javascript library maintained by Google ;)

只是为了寻找这个,我发现了一个由 Google 维护的 Java 和 Javascript 库;)

See the repo: https://github.com/googlei18n/libphonenumber

查看 repo:https: //github.com/googlei18n/libphonenumber

Also there is a demo.

还有一个演示。

Good Luck!

祝你好运!

回答by swara

The below code will extract the country code from any given phone number, the logic is implemented based on. https://en.wikipedia.org/wiki/List_of_country_calling_codes
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

    /**
     * @author swapna * This class will fetch the country code from the incoming
     *         phone number with format <+><CTRY CODE><Phone Number> based on the
     *         data from https://en.wikipedia.org/wiki/List_of_country_calling_codes
     *
     */
    public enum PhoneNumberNCtryCode {
        Instance;

        private List<Integer> forCtryCodePrefix1 = new ArrayList<Integer>();
        @SuppressWarnings("serial")
        List<Integer> forCtryCodePrefix2 = new ArrayList<Integer>() {
            {
                add(0);
                add(7);
                add(8);

            }
        };
        @SuppressWarnings("serial")
        private List<Integer> forCtryCodePrefix3 = new ArrayList<Integer>() {
            {
                add(0);
                add(1);
                add(2);
                add(3);
                add(4);
                add(6);
                add(9);
            }
        };
        @SuppressWarnings("serial")
        private List<Integer> forCtryCodePrefix4 = new ArrayList<Integer>() {
            {
                add(0);
                add(1);
                add(3);
                add(4);
                add(5);
                add(6);
                add(7);
                add(8);
                add(9);
            }
        };
        @SuppressWarnings("serial")
        private List<Integer> forCtryCodePrefix5 = new ArrayList<Integer>() {
            {
                add(1);
                add(2);
                add(3);
                add(4);
                add(5);
                add(6);
                add(7);
                add(8);
            }
        };
        @SuppressWarnings("serial")
        private List<Integer> forCtryCodePrefix6 = new ArrayList<Integer>() {
            {
                add(0);
                add(1);
                add(3);
                add(4);
                add(5);
                add(6);

            }
        };
        private List<Integer> forCtryCodePrefix7 = new ArrayList<Integer>();
        @SuppressWarnings("serial")
        private List<Integer> forCtryCodePrefix8 = new ArrayList<Integer>() {
            {
                add(1);
                add(3);
                add(4);
                add(6);
                add(9);

            }
        };
        @SuppressWarnings("serial")
        private List<Integer> forCtryCodePrefix9 = new ArrayList<Integer>() {
            {
                add(1);
                add(2);
                add(3);
                add(4);
                add(5);
                add(8);
            }
        };
        @SuppressWarnings("serial")
        private Map<Integer, List<Integer>> countryCodeMap = new HashMap<Integer, List<Integer>>() {
            {
                put(1, forCtryCodePrefix1);
                put(2, forCtryCodePrefix2);
                put(3, forCtryCodePrefix3);
                put(4, forCtryCodePrefix4);
                put(5, forCtryCodePrefix5);
                put(6, forCtryCodePrefix6);
                put(7, forCtryCodePrefix7);
                put(8, forCtryCodePrefix8);
                put(9, forCtryCodePrefix9);

            }
        };

        /**
         * This method parses the phone number using the prefix Ctry Map
         * 
         * @param phoneNumber
         * @return
         */
        public int getCtryCode(String phoneNumber) {
            String ctryCodeAtIndex1 = phoneNumber.substring(1, 2);
            Integer ctryCode = 0;
            String ctryCodeStr = "0";

            List<Integer> ctryCodeList =        countryCodeMap.get(Integer.valueOf(ctryCodeAtIndex1));
            if (ctryCodeList.isEmpty()) {
                ctryCode = Integer.valueOf(ctryCodeAtIndex1);
                return ctryCode.intValue();
            }
            String ctryCodeAtIndex2 = phoneNumber.substring(2, 3);
            for (Integer ctryCodePrefix : ctryCodeList) {
                if (Integer.valueOf(ctryCodeAtIndex2) == ctryCodePrefix) {
                    ctryCodeStr = phoneNumber.substring(1, 3);
                    ctryCode = Integer.valueOf(ctryCodeStr);
                    return ctryCode.intValue();

                }
            }
            ctryCodeStr = phoneNumber.substring(1, 4);
            ctryCode = Integer.valueOf(ctryCodeStr);
            return ctryCode.intValue();
        }

    }

回答by twid

Country code in mobile some time start with like +(plus)44, 0044, 44 and as said above some country may have variable length code. So best possible solution would be start from back as of now we know length of mobile number is 10. once you take those 10 digits, Then you can parse country code accordingly.

有时移动中的国家/地区代码以 +(plus)44, 0044, 44 开头,如上所述,某些国家/地区可能具有可变长度代码。所以最好的解决方案是从现在开始,我们知道手机号码的长度是 10。一旦你取了这 10 位数字,那么你就可以相应地解析国家代码。

回答by vainolo

While using static data structures may be considered bad practice, country codes don't change much, so I think creating a list of them as a tree and parsing the number with this tree should be an easy to implement solution.

虽然使用静态数据结构可能被认为是不好的做法,但国家/地区代码不会发生太大变化,因此我认为将它们的列表创建为树并使用该树解析数字应该是一个易于实现的解决方案。

You could also put the list of country codes in an external file so it can be easily updated without changing the application code.

您还可以将国家/地区代码列表放在外部文件中,以便在不更改应用程序代码的情况下轻松更新。

Wikipedia has the list of country codes here.

维基百科在此处提供国家代码列表。

回答by viks

If the country code is only 2 digit no. split the phone no into 2 with first substring having 2 digits and second one having the remaining 10 digit.

如果国家代码只有 2 位数字。将电话号码分成 2 个,第一个子串有 2 位数字,第二个子串有剩余的 10 位数字。

回答by Nitin Chhajer

Just doing a quick check from wikipedia, I figured that you need to do a max string search algo from the front. On a conflict, which does not seem to come, but incase, you can check the number of digits (NSN) to find the country code

只是从wikipedia进行了快速检查,我认为您需要从前面进行最大字符串搜索算法。关于冲突,这似乎不来,但如果有,您可以检查位数(NSN)以找到国家/地区代码

An optimized way would be to create buckets. As from country code list. The maximum length of country code is 4, (unless you want to go into the precision of provinces in which case it will be 7, check zone 6). and then check for the existence from 4, 3, 2, 1. This will significantly reduce your search algorithm time. But yes the data size will be bigger. A classic case of time space tradeoff

一种优化的方法是创建存储桶。从国家代码列表。国家代码的最大长度为 4,(除非你想进入省份的精度,在这种情况下它将是 7,检查区域 6)。然后从 4、3、2、1 中检查是否存在。这将显着减少您的搜索算法时间。但是是的,数据大小会更大。时间空间权衡的经典案例

回答by Janoz

If you take a look at your own link you can find the CountryCodeToRegionCodeMap class. It contains a list of probably all country codes. You could use that to create your own code to determine of the country code has a length of 1, 2 or 3. I can't believe this is the only place on the internet where such a list can be found.

如果您查看自己的链接,您可以找到CountryCodeToRegionCodeMap 类。它包含可能所有国家/地区代码的列表。您可以使用它来创建自己的代码,以确定国家代码的长度为 1、2 或 3。我不敢相信这是互联网上唯一可以找到此类列表的地方。