那麼我不知道是否有更快的方式來使用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"));
}
有沒有關於這兩個字符串,你總是可以假設任何事情?像str2始終是一個以斜槓或str1開頭的路徑,將始終包含協議和主機? –
是的,str2總是以/開頭,而str1總是爲protocol:// host [:port]/context –
'str2.startsWith(str1.substring(str1.lastIndexOf('/'))+'/')' – Andreas