#include <stdio.h>
#include <string.h>
//返回第一个子串在主串的位置,找不到返回-1
int StrMatch(char *source, char *match){
int slen=strlen(source);
int mlen=strlen(match);
int i=0,j=0;
while(i<slen && j<mlen){//当主串或者子串全部匹配完,就退出循环
if(source[i] == match[j]){//逐个比较,匹配就比较下一个
++i;
++j;
}else{//不匹配就重新回到刚开始的下一个位置
i = i-j+1;
j = 0;
}
}
if(j == mlen){//说明子串全部都匹配成功,返回子串在主串的位置
return (i-j);
}else{
return -1;
}
}
void main(){
char str[] = "hello, tom ,how are you!";
char match[] = " tom ";
int result;
result = StrMatch(str,match);
printf("-->%d
",result);
}