1. 程式人生 > >C中strstr的實現方法

C中strstr的實現方法

split pen javadoc sid rst string.h while header 沒有

做題目的時候須要自己實現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 == ‘\0‘) 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\n", res); else
printf("not find\n"); res = strstr(str, substr); if (res != NULL) printf("%s\n", res); else printf("not find\n"); 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);

感覺似乎沒有這段也是能夠輸出預期的結果的。

C中strstr的實現方法