首页 > 试题广场 >

在写一个函数,根据两文件的绝对路径算出相对路径。如 a="

[问答题]
在写一个函数,根据两文件的绝对路径算出相对路径。如 a="/qihoo/app/a/b/c/d/new.c",b="/qihoo/app/1/2/test.c',那么b相对于a的相对路径是"../../../../1/2/test.c"
推荐
public class PathCal {

 public static void main(String[] args) throws Exception {   
  
     String pathA = "/qihoo/app/a/b/c/d/new.c";  
     String pathB = "/qihoo/app/1/2/test.c";  
     System.out.println(pathRelative(pathB,pathA,""));  
 }   
  
 /** 
  * pathA相对于pathB的相对路径 递归算法: 
  */  
 public static String pathRelative(String pathA,String pathB, String tempPath) {  
     if (pathA.startsWith(pathB))  
         return pathA.replaceFirst(pathB+"/",tempPath.substring(0,tempPath.length()-3));  
     else  
         return pathRelative(pathA, pathB.substring(0, pathB.lastIndexOf("/")), "../" + tempPath);  
 }  

}

编辑于 2015-01-31 15:46:45 回复(2)
string fun(string str1, string str2)
{
    string temp = "";
    bool flag = false;
    int j;
    for (int i = 0; i < str1.size(); i++)
    {
        if (!flag && str1[i] != str2[i])
        {
            flag = true;
            j = i;
        }
        if (flag && str1[i] == '/')
        {
            temp += "../";
        }
    }
    if (temp == "") temp += '/';
    temp += str2.substr(j);
    return temp;
}


发表于 2015-08-11 14:07:48 回复(1)
源码:
运行结果:
发表于 2016-03-29 18:00:48 回复(1)
public class RelativePath {

	public static void main(String[] args) {
		
		String a="/qihoo/app/a/b/c/d/new.c";
		String b="/qihoo/app/a/b/c/d/new.c/1/2/test.c";
		String sb=getRelativePath(a, b);
		System.out.println(sb);
	}
	public static String getRelativePath(String a, String b){
		StringBuffer sb=new StringBuffer();
		String newA=a.substring(1);
		String newB=b.substring(1);
		String[] newAs=newA.split("/");
		String[] newBs=newB.split("/");
		int start=-1,end=0;
		int len=newAs.length>newBs.length?newBs.length:newAs.length;
		boolean flag=false;
		for(int i=0;i<newAs.length;i++){
			if(newAs[i].equals(newBs[0]) && flag==false){
				flag=true;
				start=i;
				break;
			}
		}	
		for(int j=0;j<len;j++){
			if(!newAs[start+j].equals(newBs[j])){
				end=j;
				break;
			}
		}
		for(int k=start;k<start+end;k++){
			sb.append("../");
		}
		for(int k=end;k<newBs.length;k++){
			sb.append(newBs[k]).append("/");
		}
		return sb.substring(0, sb.length()-1);
	}
}

发表于 2015-08-22 21:07:56 回复(1)

string Path( string b , string a )

{

    int size= b .size()< a .size()? b .size(): a .size();

    int i=1;

    int last=0;

    for (;i<size;i++)

    {

       if ( b [i]== a [i])

       {

           if ( b [i]== '/' )

           {

              last=i;

              continue ;

           }

       }

       else

       {

           break ;

       }

    }

    int num=0;

    for ( int j= a .size()-1;j>last;j--)

    {

       if ( a [j]== '/' )

       {

           num++;

       }

    }

    string str= "../" ;

    string res= "" ;

    for ( int i=0;i<num;i++)

    {

       res+=str;

    }

    for ( int j=last+1;j< b .size();j++)

    {

       res+= b [j];

    }

    return res;

 

}

发表于 2017-04-28 23:52:38 回复(0)
string fun(string str1, string str2)//str2相对于str1的相对路径
{
    string result;
    if(str1.size() == 0)
    {
        return str2;
    }
    if(str2.size() == 0)
    {
        return result;
    }

    size_t j = 0;
    for(size_t i = 0; i <str1.size(); ++i)
    {
        if(str1[i] != str2[i])
        {
            break;
        }

        if(str1[i] == '/')
        {
            j = i;
        }
    }

    result = str2.substr(j + 1);

    int counter = 0;
    for(size_t k = j + 1; k < str1.size(); ++k)
    {
        if(str1[k] == '/')
        {
            ++counter;
        }
    }

    string temp;
    for(size_t i = 0; i < counter; ++i)
    {
        temp += "../";
    }
    result = temp + result;
    return result;
}

发表于 2016-07-25 17:45:20 回复(0)
 <?php

function relativePath($aPath, $bPath) {
	$aArr = explode('/', $aPath);    //explode函数用于切分字符串,返回切分后的数组,此处用'/'切分字符串
	$bArr = explode('/', $bPath);
	$path = '';
	for($i=0;$i < count($bArr);$i++){
		if($aArr[$i] == $bArr[$i]){
			$path .='../';
			//$bArr[$i] = '';
			unset($bArr[$i]);
		}
	
	}                
	$path .=implode('/',$bArr);
	return $path;

}   

	echo relativePath('/qihoo/app/a/b/c/d/new.c', '/qihoo/app/1/2/test.c');

?>

发表于 2015-08-11 11:26:08 回复(0)
刘头像
#include<iostream>
#include<string>
using namespace std;
int main()
{
char a[100];
char b[100];
cin >> a >> b;
char* sp = "/";
string s1[20];
string s2[20];
int len1 = 0, len2 = 0;
char* p=strtok(a,sp);
while (p != NULL)
{
string s(p);
s1[len1++] = s;
p = strtok(NULL, sp);
}
p = strtok(b, sp);
while (p != NULL)
{
string s(p);
s2[len2++] = s;
p = strtok(NULL, sp);
}
int k = 0;
while (k < len1&&k < len2)
{
if (s1[k] != s2[k])
break;
k++;
}
string result;
for (int i = 1; i < len1 - k; i++)
result.append("../");
for (int i = k; i < len2; i++)
{
result.append(s2[i]);
if (i != len2 - 1)
result.append("/");
}
cout << result;

}

发表于 2015-07-14 15:23:48 回复(0)
/**
 * 在写一个函数,根据两文件的绝对路径算出相对路径。如 a="/qihoo/app/a/b/c/d/new.c",b="/qihoo/app/1/2/test.c',那么b相对于a的相对路径是"../../../../1/2/test.c"
 * @author luchunlong
 *
 * 2015年8月10日 下午1:49:02
 */
public class AbsoluteToRelativeLocation {
	
	public String convert(String path1,String path2){
		String result="";               
		path1.substring(1);                    //第一步,先除掉绝对路径的第一个“/”,以方便第二步划分
		path2.substring(1);
		String[] array1=path1.split("/");     //第二步:通过“/”划分绝对路径,并将相同的部分移除
		String[] array2=path2.split("/");
		int len=array1.length<array2.length?array1.length:array2.length;
		
		for(int i=0;i<len;i++){
			if(array1[i].equals(array2[i])){
				path1=path1.substring(path1.indexOf("/")+1);
				path2=path2.substring(path2.indexOf("/")+1);
			}else{
				break;
			}
		}
		System.out.println("不同部分:");
		System.out.println("path1:"+path1);
		System.out.println("path2:"+path2);
		
		
		String[] array3=path1.split("/");     //第三步:对第二步产生的path1进行重新划分,将每一个“XXX/”前面部分换成"。。/"
		for(int i=0;i<array3.length-1;i++){
			result+="../";
		}
		return result+path2;                  //第四步:组装结果
	}
	
	public static void main(String[] args){
		String path1="/qihoo/app/a/b/c/d/new.c";
		String path2="/qihoo/app/1/2/test.c";
		AbsoluteToRelativeLocation convertor=new AbsoluteToRelativeLocation();
		String relativePath=convertor.convert(path1, path2);
		System.out.println("relativePath:"+relativePath);
	}

}


发表于 2015-08-10 14:19:45 回复(1)
public class Re_path {
public static String getPath(String a, String b){
StringBuffer sb = new StringBuffer();
//System.out.println(a+" "+ b);
int i = 0;
for(i = 0;i < a.length();i++){
if(!(a.charAt(i) == b.charAt(i))){
break;
}
}
String str = b.substring(i);
while(i < a.length())
{
if(a.charAt(i) == '/')
{
sb.append("../");
}
i++;
}
sb.append(str);
return sb.toString();
}

public static void main(String[] args) {
// TODO Auto-generated method stub
String a ="/qihoo/app/a/b/c/d/new.c";
String b = "/qihoo/app/1/2/test.c";
String sb = getPath(a, b);
System.out.println(sb);
}

}

编辑于 2017-07-13 20:14:48 回复(0)
xwy头像 xwy
#coding:utf-8

a="/qihoo/app/a/b/c/d/new.c"
b="/qihoo/app/1/2/test.c"


def outer(a,b):
    a_list = a.split('/')
    b_list = b.split('/')

    a_max = len(a_list)
    b_max = len(b_list)
    num = min(a_max,b_max)
    path_pre = ''
    for i in range(num):
        if a_list[i] != b_list[i]:
            print path_pre + list2str(b_list[i:])
            break
        else:
            path_pre += '../'

def list2str(temp):
    str_temp = ''
    for index,item in enumerate(temp):
        if index != (len(temp)-1):
            str_temp += item + '/'
        else:
            str_temp += item
    return str_temp


outer(a,b)
            


发表于 2016-09-08 23:55:10 回复(0)
string path(string &a,string &b){
    string *p=b,*q=b;
    int lena=a.size(a);
    int lenb=b.size(b);
    int count=0;
    for(int i=0;i<lena && i<lenb;i++){
          if(a[i]=='/' &&b[i]=='/'){
              count++;
              q=p+1;
           }
          else if(a[i]!=b[i])
               break;
          p++;
    }
    p="";
    for(int i=1;i<=count;i++)
         p+="../";
   if(p=="")
        p+='/';
    p+=p+q;
    return p;
}
发表于 2016-06-03 15:46:01 回复(0)
#include<iostream>
#include<string>

using namespace std;

string result = "../";
string&  relativepath(string& str1, string& str2)
{
	int i = 0;
	while (str1[i]==str2[i])
	{
		if (str1[i]=='/')
		{
			result += "../";
		}
		++i;
	}
	result += str2.substr(i);
	return result;
}


int main()
{
	string s1 = "/qihoo/app/a/b/c/d/new.c";
	string s2 = "/qihoo/app/1/2/test.c";
	cout << relativepath(s1, s2) << endl;
	return 0;
}

发表于 2016-03-29 10:06:05 回复(0)
N.K头像 N.K
发表于 2016-03-10 19:27:17 回复(1)
答:
//大题测试,根据两个文件的绝对路径,输出文件A相对于B的相对路径
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main()
{
 vector<char> result;
 string str1,str2;
 cin>>str1;
 cin.clear();
 cin>>str2;
 int i=0;
 while(str1[i]==str2[i])
 {++i;}
 int j=0;
 int count=0;//用来记录字符'/'的个数
 for(;j<=i;++j)//统计'/'的个数
 {
  if(str1[j]=='/')
   count++;
 }
 for(;count>=0;--count)//存储相应个数的‘../’
 {
  result.push_back('.');
  result.push_back('.');
  result.push_back('/');
 }
 for(;i<str2.length();++i)
 {
  result.push_back(str2[i]);
 }
 for(int m=0;m<result.size();m++)
 {
  cout<<result[m];
 }
 cout<<endl;
 system("pause");
 return 0;
}

发表于 2016-01-04 11:12:25 回复(0)
#include <iostream>
#include <string>
using namespace std;

string relativepath(string a,string b)
{

int i=0;
while(a[i]==b[i])i++;
a=&a[i];
b=&b[i];
/*cout<<"截断后字符串为:"<<endl;
cout<<a<<endl;
cout<<b<<endl;*/
i=0;
int num=0;

while(i<a.size())
{
if(a[i++]=='/') num++;
}

string s="";
while(num--){s+="../";}
s+=b;

return s;

}

int main()
{
string a="/qihoo/app/a/b/c/d/new.c";
string b="/qihoo/app/1/2/test.c";
cout<<"原始字符串为:"<<endl;
cout<<a<<endl;
cout<<b<<endl;
cout<<"相对地址为:"<<endl;
cout<<relativepath(a,b);
return 0;
}

发表于 2015-09-29 19:50:49 回复(0)
class Solution():
    def Relativedir(self, source, dist):
        #将路径进行分裂
        source = source.split("/")
        dist = dist.split("/")
        print(source,dist)

        len_s = len(source)
        len_d = len(dist)
        #遍历至第一个不同的子路径
        for i in range(min(len_s, len_d)):
            if source[i] != dist[i]:
                break
        print(len_s, len_d, i)
        reladir = []
        #从源文件的路径向上回溯至公共路径的最低一层
        for j in range(i, len_s - 1):
            reladir.append("..")
        #向目的文件遍历
        for j in range(i, len_d):
            reladir.append(dist[j])

        return "/".join(reladir)

so = Solution()
print(so.Relativedir("/qihoo/app/a/b/c/d/new.c", "/qihoo/app/1/2/test.c"))

发表于 2015-08-26 10:13:48 回复(0)
啥头像
<pre class="prettyprint lang-cpp">string relativePath(string a, string b) { string c = ".../.../"; int pos1 = 0; // pos1、pos2标识'/'的位置 int pos2 = 0; while(pos1 != -1) { pos1 = b.find('/', pos2); pos2 = b.find('/', pos1+1); if(pos1 == -1) break; else if(pos2 == -1) { c = c + b.substr(pos1+1, b.length()-pos1-1); break; } else { string tempA = a.substr(pos1, pos2-pos1); string tempB = b.substr(pos1, pos2-pos1); if(tempA == tempB) c = c + ".../"; else { string temp = b.substr(pos1+1,b.length()-pos1-1); c = c + temp; break; } } } return c; }</pre> <br />
发表于 2015-08-14 10:52:44 回复(0)
#include <iostream> 
#include <string> 
using namespace std; 
 
void getRelativeString(const string &a, const string &b){ 
    int i = 0, j = 0; 
   while(i < a.size() && j < b.size()){     // 不相同的字符位置 
        if(a[i] == b[j]){ 
            i++; 
            j++; 
        }else break; 
    } 
    // 计算a在不同点后面有多少个/   
    int remain_a = 0; 
    while( (i = a.find_first_of('/', i)) != string::npos){  // 找到a后面还有多少'/' 结果即为a有多少个/ 那么b的前缀就有多少个../  即为pre_str 
      remain_a ++; 
        i++; 
    } 
    string pre_str = ""; 
    for(int k = 0; k < remain_a; k++){ 
        pre_str += "../"; 
    } 
 
    // 计算b的后半部分 
   // cout << remain_a << endl; 
    while(j < b.size() && b[j] != '/')j++;       // 找到b不相同的地方到上一个/的单词  结果就为pre_str 加上从该单词开始的b后面的字符串。 
   string str = b.substr(0, j); 
    str = b.substr(str.find_last_of('/')+1); 
 
    // 得到结果 
    str = pre_str + str; 
    cout << str << endl; 
 

 
int main(){ 
    string a ="/qihoo/app/a/b/c/d/new.c"; 
    string b = "/qihoo/app/1/2/test.c"; 
    getRelativeString(a, b); 
   return 0; 

发表于 2015-08-13 17:43:34 回复(0)
#define  _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

/*
在写一个函数,根据两文件的绝对路径算出相对路径。
如 a="/qihoo/app/a/b/c/d/new.c",b="/qihoo/app/1/2/test.c',
那么b相对于a的相对路径是"../../../../1/2/test.c"
*/

//sdir2为需要参考的路径,cdir为需要处理成相对路径的路径,destdir为最后的相对路径
void path(char* sdir1, char* cdir2,char* destdir){
int num = 0;

char* temp1 = sdir1;
char* temp2 = cdir2;

if (sdir1 == NULL){
destdir= NULL;
}
if (cdir2 == NULL){
destdir= sdir1;
}
while (*temp1 == *temp2){
if (*temp2 == '/'){
num++;
}
temp1++;
temp2++;
}
for (int i = 0; i < num; i++){
destdir[3 * i] = '/';
destdir[3*i+1] = '.';
destdir[3*i+2] = '.';
}
strcat(destdir, temp2);
}

int main(void){

//1.定义存储路径的路径字符串变量
char* a = "/qihoo/app/a/b/c/d/new.c";
char* b = "/qihoo/app/1/2/test.c";
char c[50] = { 0 };
path(a, b,c);

printf("c=%s\n",c);

system("pause");
return 0;
}
发表于 2015-08-11 15:40:39 回复(0)
public class FilePath {

public static void main(String[] args) {
// TODO Auto-generated method stub
String a="/qihoo/app/a/b/c/d/new.c";
String b="/qihoo/app/1/2/test.c";
System.out.println(relativePath(a,b));
}

private static String relativePath(String a, String b) {
// TODO Auto-generated method stub
String[] astrs=a.split("/");
String[] bstrs=b.split("/");
int alen=astrs.length;
int blen=bstrs.length;
int count=0;
while(count<=alen&&count<=blen){
if(!astrs[count].equals(bstrs[count])){
break;
}
count++;
}
StringBuilder path =new StringBuilder();
for(int i=count;i<alen-1;i++){
path.append("../");
}
for(int i=count;i<blen;i++){
path.append(bstrs[i]);
if(i!=blen-1){
path.append("/");
}
}
return path.toString();
}
}

发表于 2015-08-11 10:05:47 回复(0)