strstr
判断一个字符串里面是否包含另外一个字符串
我们以字符串为例
char str1[] = "hello world";
char str2[] = "world";
const char* result = strstr(str1, str2);
if (result == NULL)
printf("没有找到\n");
else
printf("找到了\n");
模拟实现strstr
我们先画一张图
红色的方框表示当前在长字符串中在比较那部分的字符串的内容
这个红色的方框要一步一步向后移动
如果发现红色方框内的内容和要匹配字符串完全一致,认为找到了
如果把所有的红色方框都找完。还没找到匹配,返回NULL,表示不包含该子串
具体代码如下
const char* my_strstr(const char* str1, const char* str2){
if (str1 == NULL || str2 == NULL){
return NULL;
}
if (*str2 == '\0'){
//str2是一个空字符串
return NULL;
}
const char* black_ptr = str1;//记录红色方框的起始位置
while (*black_ptr != '\0'){
const char* red_ptr=black_ptr;//完成红色方框内部的查找
const char* sub_ptr = str2;
while (*red_ptr != '\0'&&*sub_ptr != '\0' && (*red_ptr == *sub_ptr)){
++red_ptr;
++sub_ptr;
}
if (*sub_ptr == '\0'){
//找到了字串
return black_ptr;
}
else
++black_ptr;
}
//while循环结束也没找到
return NULL;
}
int main(){
char str1[] = "hello world";
char str2[] = "world";
const char* result = my_strstr(str1, str2);
if (result == NULL)
printf("没有找到\n");
else
printf("找到了\n");
system("pause");
return 0;
}