Home > Mobile >  How to write a URL function?
How to write a URL function?

Time:11-28

i'm new to Java, so i have a little problem here...

i need to write a function that extracts the server name from the URL It means the following: For a row of the form http://SomeServerName/abcd/dfdf.htm?dfdf=dfdf i need to isolate "SomeServerName"

  • The string may not necessarily start with http, but also with https or something else. But :// there is always
  • Consider the case when there is no more slash after :// (for example http://SomeServerName)
  • I need to use only indexOf and substring
// This is what i got so far

public static String getURL(String string) {
    int startIndex = string.indexOf('/')   2;

    int endIndex = string.indexOf("/", startIndex);

    return string.substring(startIndex, endIndex);
}

public static void main(String[] args) {
        String string = "https://SomeServerName/abcd/dfdf.htm?dfdf=dfdf";

        System.out.println(getURL(string));
    }

CodePudding user response:

String s="http://SomeServerName";
          String s1=s.substring(s.indexOf("://") 3);
          if(s1.indexOf("/")==-1) {
              System.out.println(s1);
          }else {
              System.out.println(s1.substring(0,s1.indexOf("/")));
          }

CodePudding user response:

        // Sample String s.
        String s = "http://SomeServerName/abcd/dfdf.htm?dfdf=dfdf";
        /*
           get a substring(startIndex, endIndex)
           startIndex : search for index of string "//" and add its length to get to end of it.
           endIndex: input string length.
         */
        String s1 = s.substring(s.indexOf("//") 2,s.length());
        /*
           get a substring(startIndex, endIndex)
           startIndex : 0
           endIndex : starting index of "/" if present or length of string s1
        */
        String output = s1.substring(0, s1.indexOf("/") > 0 ? s1.indexOf("/") : s1.length());
        System.out.println(output);     // output : SomeServerName
  • Related