某日用strstr函数,突然想任务不忙的时候也写写这个代码练练手,顺便记录下自己的思绪,于是产生了下面里的代码,测了几个用例还行,各位看官如果发现有误的地方,麻烦指正下~
#include "stdio.h"
char *selfstrstr(char *str1, char *str2)
{
int s1_len = strlen(str1);
int s2_len = strlen(str2);
int i,j;
if (s1_len < s2_len) {
return null;
}
int objidex = 0;
for (i = 0; i < s1_len - s2_len 1; i ) {
for (j = 0; j < s2_len; j ) {
if (str2[j] == str1[j i]) {
if (j == s2_len - 1) {
//find index
objidex = i;
return &str1[objidex];
}
continue;
} else {
break;
}
}
}
return null;
}
void main()
{
//char *test1 = "woaibeijingtiananmen";
char *test1 = "eijingtiananmen";
//char *test2 = "beijing";
char *test2 = "jing";
char *ret = selfstrstr(test1, test2);
if (ret) {
printf("good, result is %s\r\n", ret);
} else {
printf("not found, try again!\r\n");
}
}