#include <stdio.h>
#include <string.h>
#include <assert.h>
char * mystrstr(char * str1, char * str2)
{
assert(str1 && str2);
char * main = str1, *sub = str2;
int len1,len2;
len2 = strlen(sub);
if(len2 == 0)
return NULL;
len1 = strlen(main);
if(len2 > len1) {
return NULL;
}
while(len1 > 0) {
len1--;
if(len2 > len1)
return NULL;
while(*main++ == *sub++) {
if(*sub == '\0')
break;
}
if(*sub == '\0') {
if(strlen(str1) < len2) {
return str1;
} else {
return (str1+len2);
}
} else {
sub = str2;
main = ++ str1;
}
}
return NULL;
}
int main() {
char * main = "abiababdaaaefghiabgklzhaixishanabxxxx";
char * sub = "zhaixishan";
int count = 0;
char * find = mystrstr(main,sub);
while(find) {
count ++;
if(find) { // printf("\n %s\n",find);
}else {
printf("\ndonot find !!!\n");
}
find = mystrstr(find,sub);
}
printf("there is %d sub string in main string\n",count);
}
|
运行结果:
zhaixishan@zhaixishan-desktop:~/Desktop$ ./a.out
there is 1 count sub string in main string
阅读(1125) | 评论(0) | 转发(0) |