开发者

how to get by with one substring call for each case?

开发者 https://www.devze.com 2022-12-07 19:58 出处:网络
I need to write a function that extracts the server name from the URL using ONLY substring and indexOf

I need to write a function that extracts the server name from the URL using ONLY substring and indexOf

I also need to consider the case, when after :// there is no more slash:

I was told that I need to make do with ONE substring call for EACH case so that extra strings are not created and my condition: serverName.indexOf("/") > 0 is not right and also the same indexOf is being done twice, this is inefficient

public class Url {
    public static String getServerName(String url) {
        String serve开发者_JS百科rName = url.substring(url.indexOf("://") + 3);

        if (serverName.indexOf("/") > 0) {
            return serverName.substring(0, serverName.indexOf("/"));
        }

        return serverName;
    }

    public static void main(String[] args) {
        String serverAddress = "https://SomeServerName";

        System.out.println(getServerName(serverAddress));
    }
}


I am not sure I've got your idea but I tried to refactor and optimise your solution a little bit:

  • 2 calls of indexOf() for each case, 2 calls of substring() if there is another slash in a given string, otherwise 1 call of substring().

    public static String getServerName(String url) {
      String serverName = url.substring(url.indexOf("://") + 3);
    
      // do not call indexOf() twice, it's result can be stored in a variable
      int slashIndex = serverName.indexOf("/");
      if (slashIndex > 0) {
          return serverName.substring(0, slashIndex);
      }
    
      return serverName;
    }
    
  • 1 call of indexOf() and substring() for each case. Instead of using the second indexOf() method you can use for-loop to get an index of another slash:

    public static String getServerName(String url) {
      int startIndex = url.indexOf("://") + 3;
      int slashIndex = 0;
      for (int i = startIndex; i < url.length(); i++) {
          if (url.charAt(i) == '/') {
              slashIndex = i;
              break;
          }
      }
    
      if (slashIndex > 0) {
          return url.substring(startIndex, slashIndex);
      }
      return url.substring(startIndex);
    }
    
0

精彩评论

暂无评论...
验证码 换一张
取 消