/*在一個字串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; }