问题遇到的现象和发生背景
本题要求实现一个字符串查找的简单函数。
函数接口定义:
char *search( char *s, char *t );
函数search在字符串s中查找子串t,返回子串t在s中的首地址。若未找到,则返回NULL。
裁判测试程序样例:
#include <stdio.h>
#define MAXS 30
char *search(char *s, char t);
void ReadString( char s[] ); / 裁判提供,细节不表 */
int main()
{
char s[MAXS], t[MAXS], *pos;
ReadString(s);
ReadString(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 j,k,h=0;
for(j=0;t[j]!=0;j++);
j=j-1;
int i=0;
while(s[i]!=0)
{
for(i;s[i]!=t[0];i++)
{
if(s[i]==0)
return NULL;
}
k=i;
while(s[i]==t[h])
{
i++;
h++;
}
if(h-1==j)
return &s[k];
}
return NULL;
}