分类: C/C++
2010-07-30 15:34:59
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