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

全部博文(930)

文章存档

2011年(60)

2010年(220)

2009年(371)

2008年(279)

分类: C/C++

2008-11-17 21:37:18

zj@zj:~/C_parm/string/own_str/strstr$ gcc -o strcasestr strcasestr.c
cat strcasestr.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_strcasestr(const char* s1,const char* s2);
int my_strncmp(const char* s1,const char* s2,int len);

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

char* my_strcasestr(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 = my_strncmp(s1, s2, len2)) && tries--)
            s1++;
    if (nomatch)
        return NULL;
    else
        return (char *) s1; /* cast const away */
}

int my_strncmp(const char* dst,const char* src,int len)
{
    int ch1,ch2;
    len--;
    do
    {
      if ( ((ch1 = (unsigned char)(*(dst++))) >= 'A') &&(ch1 <= 'Z') )
        ch1 += 0x20;
    //printf("ch1=%c\n",ch1);

      if ( ((ch2 = (unsigned char)(*(src++))) >= 'A') &&(ch2 <= 'Z') )
        ch2 += 0x20;
    //printf("ch2=%c\n",ch2);

    }while(ch1&&ch2&&(ch1 == ch2)&&len--);
   printf("ch1-ch2=%d\n",ch1-ch2);
   return(ch1 - ch2);
}
zj@zj:~/C_parm/string/own_str/strstr$ ./strcasestr
ch1-ch2=0
the first ocu cde of CDEcd is:
CDEcd

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