/*在一个字串s1中查找一子串s2,若存在则返回子串在主串中的起始位置,不存在则返回-1。*/this
#include <stdio.h> #include <string.h> int search (char s1[],char s2[]); int main(int argc, const char * argv[]) { char s1[] = "thisis", s2[] = "si"; int result = search(s1, s2); printf("result = %i\n",result); return 0; } int search (char s1[],char s2[]) { int i = 0,j; size_t len= strlen(s2); printf("len = %zd\n",len); while (s1[i]) { for (j = 0; j < len; j++) { //依次日后遍历s2的长度,若是对应字符不一致直接跳出for循环,s1字符日后继续遍历 if (s1[i+j] != s2[j]) { break; } } //若是j等于s1的长度,则证实s1包含有字符串s2 if (j >= len) { return i; } i++; } return -1; }