c_cpp [string] strstr,在haystack heystack找到针

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp [string] strstr,在haystack heystack找到针相关的知识,希望对你有一定的参考价值。

bool is_match(const char *s, const char *p) {
    if(!s || !*s || !p) return false;
    int np = strlen(p), i = 0;
    while(i < np) {
        if(s[i] != p[i]) return false;
        i++;
    }
    return true;
}

// easy to code, but not efficient, because strlen(patt) is called many times.

char* strstr(char *big, char *patt) {
    if(!big || !*big) return NULL;
    if(!patt || !*patt) return big;
    int nb = strlen(big);       // no need to calculate length of pattern here because it is calculated in is_match().
    int i = 0;
    while(i < nb) {
        if(is_match(big + i, patt) == true) 
            return big + i;
        i++;
    }
    return NULL;
}

// better way

char* strstr(char *big, char *patt) {
    if(!big || !*big) return NULL;
    if(!patt || !*patt) return big;
    int nb = strlen(big), np = strlen(patt);
    if(nb < np) return NULL;
    int i = 0;
    while(i < nb) {
        char *p = big + i;
        int j = 0;
        while(j < np) {
            if(p[j] != patt[j]) break;
            j++;
        }
        if(j == np) return p;
        i++;
    }
    return NULL;
}

// cleaner & conciser
char* strstr(const char *heystack, const char *needle) {
    	if(!heystack) return NULL;
	if(!needle) return (char*)heystack;

	int n1 = strlen(heystack), n2 = strlen(needle);
	if(n1 < n2) return NULL;

	for(int i=0; i<=n1-n2; i++) {    // should be <= not <
	        int start = i, j = 0;
	        while(j < n2) {                  // j cannot equal to n2
	    	    if(heystack[start] != needle[j]) break;
	    	    start++;
	            j++;
	        }
	        if(j == n2) return (char*)(heystack+i);
    	}
    	return NULL;
}

以上是关于c_cpp [string] strstr,在haystack heystack找到针的主要内容,如果未能解决你的问题,请参考以下文章

c_cpp strstr.cpp

c_cpp 28.实施strStr- DifficultyEasy - 2018.8.25

strstr的模拟实现

C 标准库 - string.h之strstr使用

实现strstr函数

判断子串在主串中位置的函数——strstr函数