本题要求实现一个字符串查找的简单函数。
函数接口定义:
char *search( char *s, char *t );
函数 s e a r c h search search在字符串 s s s中查找子串 t t t,返回子串 t t t在 s s s中的首地址。若未找到,则返回 N U L L NULL 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;
}
/* 你的代码将被嵌在这里 */
输入样例1:
The C Programming Language
ram
输出样例1:
10
输入样例2:
The C Programming Language
bored
输出样例2:
-1
demo
char *search(char *s, char *t)
{
char *p1=s,*p2,*q;
while(*p1)
{
q=t;
while((*p1)&&(*p1!=*q)){p1++;}//找首字母相同
if(!(*p1)){break;} //没有找到
else{
p2=p1;
while(*p2==*q&&(*p2)!='\0')
{
p2++;q++;
}
if(*q=='\0') break;//找到该子串
else {
p1++;
}
}
}
if(!(*p1)) return NULL;
else return p1;
}