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 ofsubstring()
if there is another slash in a given string, otherwise 1 call ofsubstring()
.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()
andsubstring()
for each case. Instead of using the secondindexOf()
method you can usefor-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); }
精彩评论