算法--计算两个绝对路径之间的相对路径

来源:互联网 发布:网络机顶盒能看卫视吗 编辑:程序博客网 时间:2024/06/05 18:39

例如有两个绝度路径分别为"/qihoo/app/1/2/jtest.c"和"/qihoo/app/a/b/c/d/df/fa/new.c",计算两者之间的相对路径。

算法如下:

#include<stdio.h>#include<stdlib.h>int CalculateSperatorNum(const char* str){int count=0;for(; *str; str++){if(*str=='/')count++;}return count;}void RelativePath(const char* strA, const char* strB, char*& result){if(NULL==strA || NULL==strB)return;int sepA=CalculateSperatorNum(strA);int sepB=CalculateSperatorNum(strB);const char* ptrA=strA;const char* ptrB=strB;const char *p1=NULL, *p2=NULL;while((*ptrA==*ptrB) && *ptrA!='\0') {ptrA++; ptrB++;}if(*ptrA=='\0') return;if(sepA>sepB){ p1=ptrA; p2=ptrB;}else{ p2=ptrA; p1=ptrB;}int n=CalculateSperatorNum(p1);const char* p=p2;int len=0;while(*p++!='\0') len++;result=(char*)malloc(sizeof(char)*(n*3+len+1));int i=0;for(i=0; i<n*3; i+=3){*(result+i)='.';*(result+i+1)='.';*(result+i+2)='/';}while(*p2!='\0'){*(result+i++)=*p2;p2++;}*(result+i)='\0';}int main(int argc, char** argv){char* a="/qihoo/app/1/2/jtest.c", *b="/qihoo/app/a/b/c/d/df/fa/new.c";char* r=NULL;RelativePath(a, b, r);printf("%s\n", r);free(r);return 0;}


1 0
原创粉丝点击