查找字符中的子串

/*在一个字串s1中查找一子串s2,若存在则返回子串在主串中的起始位置,不存在则返回-1。*/

#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
",result);
    
    return 0;
}

int search (char s1[],char s2[])
{
    int i = 0,j;
    
    size_t len= strlen(s2);
    
    printf("len = %zd
",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;
}
原文地址:https://www.cnblogs.com/wm-0818/p/5275708.html