实现strstr函数
strstr函数:函数用于判断字符串str2是否是str1的子串。如果是,则该函数返回 str1字符串从 str2第一次出现的位置开始到 str1结尾的字符串;否则,返回NULL。
const char* strstr(const char* str1, const char* str2)
const char* my_Strstr(const char* str1, const char* str2) {
assert(str1 != '\0' && str2 != '\0');
if (str2 == '\0') { //防止str2是空字符串
return NULL;
}
char* black = str1;
while (*black != '\0') {
char* red = black;
char* sub = str2;
while (*red != '\0' && *sub != '\0' && (*red == *sub)) {
//跳出这个while的前提是red跑完了,或者sub跑完了,亦或者*sub不等于*red
red++;
sub++;
}
//sub跑完了,那就找到了,返回black
if (*sub == '\0') {
return black;
}
//red跑完了,那就是没找到
if (*red == '\0') {
return NULL;
}
//两者不相等,black往后移一位继续比
black++;
}
return NULL;
}