字符串倒序查找字串

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


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

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

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

  11.     return 0;
  12. }

  13. char *
  14. myStrrstr(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;

  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.     p = haystack + hay_len - need_len;

  28.     while (p >= haystack) {
  29.         for (i = 0; i < need_len; i++)
  30.             if (p[i] != needle[i])
  31.                 goto next;
  32.         return (char *)p;
  33.         
  34.         next:
  35.             p--;
  36.     }

  37.     return NULL;
  38. }

上一篇:字符串反转
下一篇:字符串正序查找子串