今天朋友出了个当时他进他们公司前面试的题,他是php程序员,这题是他唯一答得上的两个算法题之一。
题目如下:
文件1路径:c:/user/edit/images/a.jsp
文件2路径: c:/user/add/user.jsp
用代码算出a.jsp和user.jsp的相对路径。
我对这题很有兴趣,于是用java做了下,功能已实现,帖出代码分享下,供初学者学习。
/**
* <p>Title: RelativeLocation.java</p>
* <p>Description: 获取指定文件相对于另一个文件的相对路径</p>
* <p>Copyright: Copyright (c) 2010</p>
* <p>Company: JAGO Software</p>
* @author DengHuaFeng
* @date 2010-5-28
* @version 1.0
*/
public class RelativeLocation{
public static void mian(String[] args) {
System.out.println(RelativeLocation.getRelativeLocation("c:/user/edit/images/a.jsp", "c:/user/add/user.jsp"));
System.out.println(RelativeLocation.getRelativeLocation("c:/user/add/user.jsp", "c:/user/edit/images/a.jsp"));
}
/**
* 获取文件2相对文件1的路径
* @param location1 文件1的绝对路径
* @param location2 文件2的绝对路径
* @return
*/
public static String getRelativeLocation(String location1,String location2){
String[] lc1=(location1.substring(location1.indexOf(":")+2)).split("/");//去除盘符 例:去除C:/
String[] lc2=(location2.substring(location2.indexOf(":")+2)).split("/");//去除盘符 例:去除C:/
String locString="";//相对路径变量声明
int start=0;//连接文件2路径的开始位置
//取得“../”的连接串
for (int i = 0; i < lc1.length; i++) {
if(i!=lc2.length){
if(!lc1[i].equals(lc2[i])){
locString="../"+locString;
if(start==0){
start=i;
}
}
}else{
locString="../"+locString;
}
}
for (int i = start+1; i < lc2.length; i++) {
locString=locString+lc2[i];
if(i+1!=lc2.length){
locString=locString+"/";
}
}
System.out.println("相对路径:"+locString);
return locString;
}
}
注:如需转载,请注明出处,以上有什么问题解答不对,欢迎交流解答!Email:denghuafeng@live.cn