查找子串substr()函数的实现——循环

实现查找子串的substr(char *s1, char *s2)函数。

如果在s1中找到了s2,就返回位置;否则返回-1。

int hjd_substr(char *s1, char *s2)
{
    int nResult = -1;
    int i=0, j=0;
    while ((*(s1+i)!='\0')&&(*(s2+j)!='\0'))
    {
        if(*(s1+i)==*(s2+j))
        {
            i++;
            j++;
        }
        else
        {
            i++;
            j=0;
        }
    }
    if(*(s2+j)=='\0')
        nResult = i-j;
    else
        nResult=-1;
    return(nResult);
}

测试成功。


版权声明:本文为chengeng_jd原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。