Implement strStr()

Implement strStr().

Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.

思想:一个一个匹配,注意终止条件;要相对严格限制

  1. char *strStr(char *haystack, char *needle) {
  2. int i=0;
  3. int hlen = strlen(haystack);
  4. int nlen = strlen(needle);
  5. while(i<=hlen-nlen) {
  6. char *p = haystack;
  7. char *q = needle;
  8. while(*p!='\0' && *p == *q) {
  9. p++;
  10. q++;
  11. }
  12. if(*q=='\0') {
  13. return p-(q-needle);
  14. } else {
  15. haystack++;
  16. i++;
  17. }
  18. }
  19. return NULL;
  20. }
posted @ 2014-08-23 18:07  purejade  阅读(67)  评论(0编辑  收藏  举报