问题链接:
#include
#include
int strStr(char * haystack, char * needle){
int i;
int haystack_len = strlen(haystack);
int needle_len = strlen(needle);
if(needle_len > haystack_len) //检查字符长度,后面的字符比前面的字符长度大,直接返回-1
return -1;
for(int i = 0; i < haystack_len; i++) {
if (strncmp(haystack, needle,needle_len) == 0 ) {
return i;
}
++haystack; // 移动指针位置,这个是关键
printf(" i = %d haystack = %s \n",i , haystack );
}
return -1;
}
int main(char *agrs , char *argv[]) {
int t1 = strStr("tdghellotest", "test");
int t2 = strStr("testhellotest", "test");
printf(" t1 = %d t2 = %d \n", t1, t2);
}