从父串中找到字串 c代码实现

/*
昨天师兄笔试题,遇到从父串中找到字串的位置,没有写出来
今天早晨用了一个小时调试编写
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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值