字符串正序查找子串

1885阅读 0评论2011-05-20 onezeroone
分类:C/C++


  1. #include <stdio.h>
  2. #include <string.h>

  3. char *myStrstr(const char *haystack, const char *needle);

  4. int
  5. main(void)
  6. {
  7.     char *s = "Hello world";
  8.     char *t = "ll";
  9.     char *r = myStrstr(s, t);
  10.     printf(r);

  11.     return 0;
  12. }

  13. char *
  14. myStrstr(const char *haystack, const char *needle)
  15. {
  16.     if (NULL == haystack || NULL == needle)
  17.         return NULL;

  18.     size_t i;
  19.     size_t hay_len, need_len;
  20.     const char *p = haystack;

  21.     hay_len = strlen(haystack);
  22.     need_len = strlen(needle);

  23.     if (need_len == 0)
  24.         return (char *)haystack;

  25.     if (hay_len < need_len)
  26.         return NULL;

  27.     while (p <= haystack + hay_len - need_len) {
  28.         for (i = 0; i < need_len; i++)
  29.             if (p[i] != needle[i])
  30.                 goto next;
  31.         return (char *)p;

  32.         next:
  33.             p++;
  34.     }

  35.     return NULL;
  36. }


上一篇:字符串倒序查找字串
下一篇:字符串化大写