函数接口定义:
char *search( char *s, char *t );
函数search在字符串s中查找子串t,返回子串t在s中的首地址。若未找到,则返回NULL。
题目代码
#include <stdio.h>
#define MAXS 30
char *search(char *s, char *t);
int main()
{
char s[MAXS]="The C Programming Language";
char t[MAXS]="ram";
char *pos;
pos = search(s, t);
if ( pos != NULL )
printf("%d\n", pos - s);
else
printf("-1\n");
return 0;
}
/*此法比较粗暴,两层循环直接遍历对比主串和子串,
严蔚敏数据结构书内有介绍KMP算法,此法闪耀着智慧之光*/
char *search(char *s, char *t)
{
char *pos=s; // pos值为每次比较主串的开始处
char *p=pos, *q=t;
while(*pos){
while(*q){
if(*p == *q){
p++;
q++;
}
else
break; // 子串虽未遍历完,但已遇到不等的字符
}
if( (*p != *q)&&(*q) ){
// 内循环因字符不等而退出,且子串未走到结束标志处,继续比较
pos++;
p = pos;
q = t;
}
else
break; // 已找到,跳出外循环
}
if(*pos=='\0') // 若外循环因主串走到结束标志处而退出,则未找到
pos = NULL;
return pos;
}