/*
昨天师兄笔试题,遇到从父串中找到字串的位置,没有写出来
今天早晨用了一个小时调试编写
2013.10.14
*/
/*
fp : father'starting postion
sp: son'beginning postion
count: sp' length
this function will return 0 when it complete,otherwise
return -1
*/
/*
使用二级指针可以返回找到子字符串的位置;
*/
static int cmpstr(char ** fp,char **sp,int count)
{
int i = 0;
if(!*fp||!*sp)//判断指针是否为空
return -1;
char * fp1 = *fp,*sp1 = *sp;
int fcount = 0;
while(*fp1++);
fcount = fp1 - *fp;//
fp1 = *fp;
if(fcount-1<count)
return -1;
// printf("%c",*fp);
// printf("%c",*sp);
for(;i<count;i++)
{
// printf("(%c %c)",fp1[i],*sp[i]);
if(fp1[i] != sp1[i])//查看是否匹配
{
return -1;
}
}
if(i == count)//匹配返回
return 0;
}
/*
fp :father'starting postion return substring postion
sp :son'beginning postion
count: sp' length
this function will return 0 when it find that,otherwise
return -1
example father'string "aghjunim" son 's string "hjun"
*/
static int findsonpos(char **fp,char ** sp,int count)
{
if(!*fp||!*sp)
return -1;
char * fp1 = *fp,*sp1 = *sp;
int fcount = 0;
int i = 0;
while(*fp1++);
fcount = fp1 - *fp;//parent string中字符个数
fp1 = *fp;
if(fcount-1<count)//parent 中字符个数必须大于字串
return -1;
while(*fp1)//从父串第一个字符开始遍历
{
// printf("%c",*fp1);
if(cmpstr(&fp1,&sp1,count)==0)//用子串对父串遍历
{
*fp = fp1;//返回字串在父串中的位置
return 0;
}
fp1++;
}
if(NULL == *fp1)
return -1;
}
int main(int argc,char ** agv)
{
char * fp = "yoedafp";
char *sp = "eda";
char * sp1 = sp;
while(*sp1++);
if(findsonpos(&fp,&sp,sp1-sp-1)==0)
{
for(int i = 0; i < sp1-sp-1;i++)
printf("%c",fp[i]);
printf("\n");
}
else
printf("no find substring\n");
return 0;
}