1 # include<iostream> 2 # include<cstdio> 3 # include<string> 4 using namespace std; 5 int index(char *a,char *b) 6 { 7 int n=0;//父串偏移量,初始为0 8 while(a[n]!=‘\0‘) 9 { 10 int m = n; 11 int k; //子串偏移量 12 for(k = 0; b[k]!=‘\0‘; k++) 13 { 14 if(a[m++]!=b[k]) //不匹配,马上停止 15 { 16 break; 17 } 18 } 19 if(b[k]==‘\0‘)//匹配成功 20 { 21 return n; 22 } 23 n++;//父串,开始移动 24 } 25 return -1; 26 } 27 int main() 28 { 29 char *a = "abcdef"; 30 char *b = "cdef"; 31 cout<<index(a,b)<<endl; 32 }
时间: 2024-11-17 00:31:24