What is the fastest way to get the domain/host name from a URL?

前端 未结 8 976
不知归路
不知归路 2020-12-08 15:48

I need to go through a large list of string url\'s and extract the domain name from them.

For example:

http://www.stackoverflow.com/questions

8条回答
  •  佛祖请我去吃肉
    2020-12-08 16:31

    There is only an another way to get the host

    private String getHostName(String hostname) {
        // to provide faultproof result, check if not null then return only hostname, without www.
        if (hostname != null) {
            return hostname.startsWith("www.") ? hostname.substring(4) : getHostNameDFExt(hostname);
        }
        return hostname;
    }
    
    private String getHostNameDFExt(String hostname) {
    
        int substringIndex = 0;
        for (char character : hostname.toCharArray()) {
            substringIndex++;
            if (character == '.') {
                break;
            }
        }
    
        return hostname.substring(substringIndex);
    
    }
    

    Now we've to pass the hostname in function after extract from URL

    URL url = new URL("https://www.facebook.com/");
    String hostname = getHostName(ur.getHost());
    
    Toast.makeText(this, hostname, Toast.LENGTH_SHORT).show();
    

    The output would be: "facebook.com"

提交回复
热议问题