2017-09-10 30 views
0

在類(Java8)中,我有一個表示HTTP URL的字符串,例如, String str1="http://www.foo.com/bar",以及包含請求URI的另一個字符串,例如str2="/bar/wonky/wonky.html"確定請求URI是否在另一個URL內的快速java例程

代碼執行的最快方式是確定str2是否在str1的上下文中(例如上下文是/ bar),然後構造完整的url String result = "http://www.foo.com/bar/wonky/wonky.html"

+0

有沒有關於這兩個字符串,你總是可以假設任何事情?像str2始終是一個以斜槓或str1開頭的路徑,將始終包含協議和主機? –

+0

是的,str2總是以/開頭,而str1總是爲protocol:// host [:port]/context –

+0

'str2.startsWith(str1.substring(str1.lastIndexOf('/'))+'/')' – Andreas

回答

0

那麼我不知道是否有更快的方式來使用String.indexOf()。下面是我想到一個辦法涵蓋了你給的例子(demo):

public static boolean overlap(String a, String b_context) { 
    //Assume the a URL starts with http:// or https://, the next/is the start of the a_context 
    int root_index = a.indexOf("/", 8); 
    String a_context = a.substring(root_index); 
    String a_host = a.substring(0, root_index); 
    return b_context.startsWith(a_context); 
    } 

下面是一個使用邏輯,但兩個URL如果它們重疊或合併,如果他們不拋出異常相同的功能

public static String combine(String a, String b_context) { 
    //Assume the a URL starts with http:// or https://, the next/is the start of the a_context 
    int root_index = a.indexOf("/", 8); 
    String a_context = a.substring(root_index); 
    String a_host = a.substring(0, root_index); 
    if(b_context.startsWith(a_context)) { 
     return a_host + b_context; 
    } else { 
     throw new RuntimeException("urls do not overlap"); 
    } 
    } 

這裏是使用的例子他們

public static void main(String ... args) { 
    System.out.println(combine("http://google.com/search", "/search?query=Java+String+Combine")); 
    System.out.println(combine("http://google.com/search", "/mail?inbox=Larry+Page")); 
    } 
+0

'lastIndexOf('/')'會比'indexOf(「/」,8)'更好。 ---在第一個例子中,'a_host'的含義是什麼? – Andreas

+0

那不是假設str1從來沒有另一個'/'? indexOf(「/」,8)假定總是有第三個斜槓。 –

+0

OP在[comment]中說過(https://stackoverflow.com/questions/46137040/fast-java-routine-to-determine-if-request-uri-is-within-another-url#comment79236376_46137040):* str1是總是protocol:// host [:port]/context *。所以根據OP,這個假設是有效的。如果情況並非如此,那麼你的代碼也會出錯,因爲'a_context'將包含的不僅僅是上下文路徑。 – Andreas

相關問題