Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4729458
  • 博文数量: 930
  • 博客积分: 12070
  • 博客等级: 上将
  • 技术积分: 11448
  • 用 户 组: 普通用户
  • 注册时间: 2008-08-15 16:57
文章分类

全部博文(930)

文章存档

2011年(60)

2010年(220)

2009年(371)

2008年(279)

分类: C/C++

2008-11-17 21:35:46

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

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