正在装载数据…… 前些日子面试,对自己当时写的strstr函数不满意,重新写了一个: char *strstr_my(const char *src,const char *dest) { const char *pcur = NULL; const char *pcmp = dest; char a,b; if(!(a = *src)) //src为空退出 return NULL; if(!(b = *pcmp)) return NULL; //dest为空退出 while(a = *src++) //src循环 { if(a == b) //寻找与dest第一个字符相等 { pcur = src; //用另一个指针跟踪 pcmp++; do { a = *pcur++; if(!(b = *pcmp++)) break; }while(a == b); if((!a && !b) || (a && !b)) //如果比较成功退出循环 { pcur = src-1; break; } //否则将pcmp,b恢复 pcmp = dest; b = *dest; pcur = NULL; } } //如果src有值就寻找成功 if(pcur != NULL) return (char *)pcur; return NULL; } 下面的strstr的源码: char * strstr (phaystack, pneedle) const char *phaystack; const char *pneedle; { const unsigned char *haystack, *needle; chartype b; const unsigned char *rneedle; haystack = (const unsigned char *) phaystack; if ((b = *(needle = (const unsigned char *) pneedle))) { chartype c; haystack--; /* possible ANSI violation */ { chartype a; do if (!(a = *++haystack)) goto ret0; while (a != b); } if (!(c = *++needle)) goto foundneedle; ++needle; goto jin; for (;;) { { chartype a; if (0) jin:{ if ((a = *++haystack) == c) goto crest; } else a = *++haystack; do { for (; a != b; a = *++haystack) { if (!a) goto ret0; if ((a = *++haystack) == b) break; if (!a) goto ret0; } } while ((a = *++haystack) != c); } crest: { chartype a; { const unsigned char *rhaystack; if (*(rhaystack = haystack-- + 1) == (a = *(rneedle = needle))) do { if (!a) goto foundneedle; if (*++rhaystack != (a = *++needle)) break; if (!a) goto foundneedle; } while (*++rhaystack == (a = *++needle)); needle = rneedle; /* took the register-poor aproach */ } if (!a) break; } } } foundneedle: return (char *) haystack; ret0: return 0; } 本文来源:http://blog.csdn.net/pSK_LB/archive/2007/08/02/1722851.aspx
|