strstr(str1,str2) 函数用于判断字符串str2是否是str1的子串。如果是,则该函数返回str2在str1中首次出现的地址;否则,返回NULL。比如如下代码的运行结果就是:cde
#include <stdio.h>
#include <windows.h>
#include <string.h>
int main(){
char str1[] = "abcde";
char str2[] = "cd";
char *str=strstr(str1, str2);
printf("%s\n", str);
system("pause");
return 0;
}
接下来模拟实现这个函数:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <windows.h>
#include <string.h>
#include <assert.h>
char *Mystrstr(const char *str1, const char *str2){
assert(str1);
assert(str2);
while (*str1){//只要str1的指向不是'\0'那么就继续比较
const char *move_str1 = str1;//赋值为当前str1
const char *move_str2 = str2;//赋值为str2(固定不变)的值
while (*move_str1 == *move_str2&&*move_str1&&*move_str2){//让字符依次比较直到不相等或某个串结束
move_str1++;
move_str2++;
}
if (*move_str2 == '\0'){//move_str2指向了'\0'说明找到了
return str1;//返回在str1中首次出现的地址
}
str1++;
}
return NULL;
}
int main(){
char str1[] = "abcde";
char str2[] = "bc";
char *str=Mystrstr(str1, str2);
printf("%s\n", str);
system("pause");
return 0;
}
这个函数的思想是这样的:让字符串str2和字符串str1从第一个字符开始比较,如果相等就返回,不相等就让字符串str2和字符串str1继续比较(这次str1从上次比较后+1字符处开始进行比较,str2继续从第一个字符开始比较)。
函数中的str1与str2的作用是记录两个字符串要从哪个字符开始比较,而move_str1和move_str2则用来比较,所以就需要两层循环,最后相等,返回值就是str1。