将子串在母串中第一次出现的位置找出来。
图1:在母串中第pos个位置定位子串的算法
图2:从母串中第pos个位置获得长度为len的子串
Input
若干对字符串,每对字符串占一行并用一个空格分开。前一个字符串为母串,后者为子串。字符串只包含英文字母的大小写。每个字符串不超过98个字符。
Output
输出子串在母串中首次出现的位置,如果母串中不包含子串则输出0。每个整数占一行。
Sample Input
ACMCLUB ACM
DataStructure data
domybest my
Sample Output
1
0
3
HINT
提示: 可以使用C语言中的字符数组来表示SString结构,不过需要注意的是数据从下标1的单元开始存储。由于C语言中的字符串是以最后一个为’\0’来标定字符串结尾,同时也没有存储字符串长度。因而算法4-3中的Sub[0]=len应当改为Sub[len+1] = ‘\0’; 总结: C语言中的字符串实际上是字符数组,以’\0’作为字符串结尾。而书中算法描述实际上与C++中的string更为接近。
#include <bits/stdc++.h>
using namespace std;
const int maxlen=100;
char z[maxlen] , m[maxlen];
int Index(char S[],char T[]);
int main()
{
while(scanf("%s %s",m,z)!=EOF)
{
printf("%d\n",Index(m,z));
}
return 0;
}
int Index(char ch1[],char ch2[])
{
int i=1,j=1;
while( i<=strlen(ch1) && j<=strlen(ch2) )
{
if(ch1[i-1]==ch2[j-1])
{
++i;
++j;
}
else
{
i=i-j+2;
j=1;
}
}
if(j==(strlen(ch2)+1))
return i-strlen(ch2);
else
return 0;
}
个人感觉写的不好,想的是另一种方法,和直接插入排序有一些想象,以后试