判断主串中子串的位置,若是主串的子串,则返回其在主串中的位置,否则做出相应回应。
#include<stdio.h>
#include<string.h>
#include<malloc.h>
#define Maxnum 100
typedef struct
{
char ch[Maxnum];
int length;
}string;
int index(string *s1,string *s2)
{
int i=0,j=0;
while((i<s1->length)&&(j<s2->length))
{
if(s1->ch[i]==s2->ch[j]) {i++;j++;} //继续比较后续字符
else {i=i-j+1;j=0;} //i移动到本次比较开始时的后一个位置,j返回子串头的位置
}
if(j>=s2->length) return i-s2->length+1; //返回位序号
else return -1;
}
int main()
{
string *s1,*s2;
s1=(string*)malloc(sizeof(string));
s2=(string*)malloc(sizeof(string));
printf("输入主串s1:\n");
gets(s1->ch);
printf("输入子串s2:\n");
gets(s2->ch);
s1->length=strlen(s1->ch);
s2->length=strlen(s2->ch);
int k=index(s1,s2);
if(k==-1)
printf("s2不是s1的子串!");
else
printf("s2是s1的子串,且其在主串中的位置是:%d\n",k);
}