C中strstr的实现方法

做题目的时候须要自己实现strstr函数

/************************************************************************/
/*       编写函数IND。让它推断一个字符串是否为还有一个字符串的子串的功能。若是则返回第一次出现的起始位置,否则返回0。  
/*
/************************************************************************/

#include <stdio.h>
#include <assert.h>

const char * IND(const char * str, const char * substr)
{
    assert(substr != NULL && str != NULL);
    const char * psub = substr;
    const char * pstr = str;

    while (*pstr)
    {
//      if (*pstr != *psub)
//          continue;

        const char * tmp = pstr;
        while (*tmp++ == *psub++);

        if (*psub == '')
            return pstr;

        psub = substr;
        pstr++;
    }

    return NULL;
}

int main()
{
    //char * substr = "hello";
    char * substr = "";
    char * str = "skljdfhellosjdlf";

    const char * res = IND(str, substr);
    if (res != NULL)
        printf("%s
", res);
    else
        printf("not find
");

    res = strstr(str, substr);
    if (res != NULL)
        printf("%s
", res);
    else
        printf("not find
");

    return 0;
}

这是微软提供的库函数版本号

/***
*strstr.c - search for one string inside another
*
*       Copyright (c) Microsoft Corporation. All rights reserved.
*
*Purpose:
*       defines strstr() - search for one string inside another
*
*******************************************************************************/

#include <cruntime.h>
#include <string.h>

/***
*char *strstr(string1, string2) - search for string2 in string1
*
*Purpose:
*       finds the first occurrence of string2 in string1
*
*Entry:
*       char *string1 - string to search in
*       char *string2 - string to search for
*
*Exit:
*       returns a pointer to the first occurrence of string2 in
*       string1, or NULL if string2 does not occur in string1
*
*Uses:
*
*Exceptions:
*
*******************************************************************************/

char * __cdecl strstr (
        const char * str1,
        const char * str2
        )
{
        char *cp = (char *) str1;
        char *s1, *s2;

        if ( !*str2 )
            return((char *)str1);

        while (*cp)
        {
                s1 = cp;
                s2 = (char *) str2;

                while ( *s1 && *s2 && !(*s1-*s2) )
                        s1++, s2++;

                if (!*s2)
                        return(cp);

                cp++;
        }

        return(NULL);

}

得到的效果是一致的, 只是。 我们这里没有使用强制类型转化将const char * 转化为 char *类型,(事实上从这点上来看, C中的const仅仅是一个纸老虎, 一个强制类型转换就没了<-_->!!)
库函数代码中

 if ( !*str2 )
            return((char *)str1);

感觉似乎没有这段也是能够输出预期的结果的。

原文地址:https://www.cnblogs.com/cxchanpin/p/7284380.html