PTA查找子串

函数search在字符串s中查找子串t,返回子串t在s中的首地址。若未找到,则返回NULL。

#include<stdio.h>
char *search(char *s, char *t);
int main()
{
	char s[30],t[30],*pos;
	scanf("%s",&s);
	scanf("%s",&t);
	pos=search(s,t);
	if(pos!=NULL)
		printf("%d\n",pos-s);
	else
		printf("-1\n");
	return 0;
}
char *search(char *s, char *t)
{
	int i=0,k=0,Slen=0,Tlen=0;
	while(s[i]!='\0'){
		Slen++;
		i++;
	}
	while(t[k]!='\0'){
		Tlen++;
		k++;
	}
	k=0,i=0;
	while(i<Slen&&k<Tlen)
	{
		if(s[i]==t[k]){
			k++;
			i++;
		}else{
			k=0;
			i=i-k+1;
		}
	}
	if(k>=Tlen){
		return s+i-k;
	}else{
		return NULL;
	}
}

版权声明:本文为MysteriousL原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。