求子串位置的定位函数

// 串的模式匹配.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include<iostream>
#include<string>
using namespace std;
int Index(char S[],char T[],int pos)
{
 //返回子串T在主串S中第pos个字符之后的位置.若不存在,则函数值为0
 //其中,T非空,i<=pos<=StrLength(S).
 int i=pos;
 int j=1;
 int m,n;
 m=strlen(S);
 n=strlen(T);
/* cout<<m<<" "<<n<<endl;*/
 while(i<=m && j<=n){
  if(S[i]==T[j]) {++i;++j;} //继续比较后续字符
  else {i=i-j+2;j=1;}     //指针后退重新开始匹配
 }
/* cout<<i<<" "<<j<<endl;*/
 if(j>n) return i-n;
 else return 0;
}

int main(int argc, char* argv[])
{
 //string CS,CT;
 char CS[200],CT[100];
 int pos;
 cout<<"请输入主串"<<endl;
 scanf("%s",CS);
 cout<<"请输入子串"<<endl;
 scanf("%s",CT);
 pos=Index(CS,CT,1);
 cout<<pos<<endl;
 return 0;
}
 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值