Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1363349
  • 博文数量: 704
  • 博客积分: 10140
  • 博客等级: 上将
  • 技术积分: 6230
  • 用 户 组: 普通用户
  • 注册时间: 2010-07-15 20:41
文章分类

全部博文(704)

文章存档

2013年(1)

2012年(16)

2011年(536)

2010年(151)

分类: C/C++

2010-07-30 15:34:39

zj@zj:~/C_parm/string/own_str/strstr$ cat strstr.c
/*
 *The strstr() function finds the first occurrence of the substring
 *needle in the string haystack. The terminating '\0' characters
 *are not compared.
*strstr.c
*/


#include<stdio.h>
#include<string.h>
#include<stdlib.h>

char* my_strstr(const char* s1,const char* s2);

int main()
{
  char* str1 = "abcdefcde";
  char* str2 = "cde";
  printf("the first ocu %s of %s is:\n%s\n",str2,str1,my_strstr(str1,str2));
  exit(EXIT_SUCCESS);
}

char * my_strstr(const char * s1, const char * s2)
{
    int len2 = strlen(s2); /* 获得待查找串的长度*/
    int tries; /* maximum number of comparisons */
    int nomatch = 1; /* set to 0 if match is found */
   
    tries = strlen(s1) + 1 - len2; /*此处说明最多只用比较这么多次,*/
    if (tries > 0)
        while (( nomatch = strncmp(s1, s2, len2)) && tries--)
            s1++;
    if (nomatch)
        return NULL;
    else
        return (char *) s1; /* cast const away */
}
zj@zj:~/C_parm/string/own_str/strstr$ ./strstr
the first ocu cde of abcdefcde is:
cdefcde
阅读(1072) | 评论(0) | 转发(0) |
0

上一篇:c strchr strrchr

下一篇:c strcasestr

给主人留下些什么吧!~~