/1、模拟实现strstr;
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <assert.h>
char* My_Strstr(const char* str1, const char* str2)
{
char *cp = (char*)str1;
char *substr = (char*)str2;
char *s1 = NULL;
assert(*str1 != NULL);
assert(*str2 != NULL);
if(*str2 == '\0')
{
return NULL;
}
while(*str2)
{
s1 = cp;
substr = str2;
while(*s1 && *substr && *s1 == *substr)
{
s1++;
substr++;
}
if(*substr == '\0')
{
return cp;
}
cp++;
}
return 0;
}
int main()
{
const char arr1[] = "This is a simple string!";
const char arr2[] = "simple";
printf("%s\n",My_Strstr(arr1, arr2));
system("pause");
return 0;
}
展示结果如下:
2、模拟实现strcmp;
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
int My_Strcmp(const char* src, const char* dst)
{
int ret = 0;
while(!(ret = *(unsigned char*)src - *(unsigned char*)dst) && *dst)
{
++src;
++dst;
}
if(ret < 0)
{
ret = -1;
}
else if(ret > 0)
{
ret = 1;
}
return ret;
}
int main()
{
char arr1[] = "hello,bit!";
char arr2[] = "z";
My_Strcmp(arr1, arr2);
printf("%d\n",My_Strcmp(arr1,arr2));
system("pause");
return 0;
}
展示结果如下: