in my homework I need to extract the server name from the url
at the same time, I need to take into account that there may not be a slash after the server name
I'm not allowed to use a loop
At the same time, I am once again trying to redo a remark from my teacher:
"Now substring can be done twice (if it goes into if). You need to make sure that only one substring is made for any variant of the function execution"
how can this be fixed? I've tried everything
public class Url {
public static String getServerName(String url) {
int index1 = url.indexOf("://") 3;
String serverName = url.substring(index1);
int index2 = serverName.indexOf("/");
if (index2 >= 0) {
return url.substring(index1, index1 index2);
}
return serverName;
}
public static void main(String[] args) {
String url = "https://SomeServerName";
System.out.println(getServerName(url));
}
}
CodePudding user response:
public class Url {
public static String getServerName(String url) {
int index1 = url.indexOf("://") 3;
int index2 = url.indexOf("/", index1);
if (index2 >= 0) {
return url.substring(index1, index2);
}
return url.substring(index1);
}
public static void main(String[] args) {
String url = "https://SomeServerName";
System.out.println(getServerName(url));
}
In this modified version, we first find the index of the first '/' character after the "://" substring, and then use it to extract the server name either as a substring from index1 to index2, or as a substring from index1 to the end of the string if index2 is not found. This ensures that only one substring is made, regardless of whether the '/' character is present in the URL or not.