题目描述:给出一个函数: a = “/qihoo/app/a/b/c/d/new.c”; b = "/qihoo/app/1/2/test.c"; 输出b相对于a的相对路径: ../../../../1/2/test.c
#include <iostream> #include <string> #include <algorithm> #include <cstring> using namespace std; const int MAX = 100; int index;// 标记下标含有'/' int index_b; void Path_To(string &a,string &b) { int num_a = 0; int num_b = 0; int pos_a[MAX] = {0}; //记录字符串中/的位置 int pos_b[MAX] = {0}; for(unsigned int i=0;i<a.size();i++) { if(a[i] == '/') { pos_a[index++] = i; num_a++; } } for(unsigned int j=0;j<b.size();j++) { if(b[j] == '/') { pos_b[index_b++] = j; num_b++; } } //用于存放子字符串 string from[num_a]; string to[num_b]; /** 测试输出字符'/'的位置 for(int k = 0;k<num_a;k++) cout << pos_a[k] << " "; cout << endl; for(int l = 0;l<num_b;l++) cout << pos_b[l] << " "; cout << endl; */ //截取子字符串 for(int num=1;num<=num_a;num++) { from[num-1] = a.substr(pos_a[num-1]+1,pos_a[num]-pos_a[num-1]-1); } for(int num=1;num<=num_b;num++) { to[num-1] = b.substr(pos_b[num-1]+1,pos_b[num]-pos_b[num-1]-1); } /* for(int i=0;i<num_a;i++) cout << from[i] << " : "; cout << endl; for(int i=0;i<num_b;i++) cout << to[i] << " : "; cout << endl; */ int flag = 0;//b字符串 有多少不同于a的 for(int k=0;k<num_b;k++) { if(!(from[k].compare(to[k]))) { flag++; } } //相对子字符串 b = b.substr(pos_b[flag]+1); flag += (num_a-num_b); for(int i=0;i<flag;i++) cout<< "../"; cout << b << endl; } int main() { string a = "/qihoo/app/a/b/c/d/new.c"; string b = "/qihoo/app/1/2/test.c"; Path_To(a,b); return 0; }
时间: 2024-10-12 03:49:11