Chinaunix首页 | 论坛 | 博客
  • 博客访问: 357962
  • 博文数量: 100
  • 博客积分: 2500
  • 博客等级: 大尉
  • 技术积分: 1209
  • 用 户 组: 普通用户
  • 注册时间: 2011-04-15 21:24
文章分类

全部博文(100)

文章存档

2011年(100)

分类: C/C++

2011-05-20 13:37:23


  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. }


阅读(1759) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~