模拟strcpy
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<windows.h>
#include<assert.h>
char* my_strcpy(char* x, char* y)
{
assert(x);
assert(y);
char* p2 = x;
while (*y != '\0')
{
*x++ = *y++;
}
*x = *y;
return p2;
}
int main()
{
char p[10] = { 0 };
char *p1 = "hello1234";
char *n = my_strcpy(p, p1);
system("pause");
return 0;
}
模拟strcat
#include<stdio.h>
#include<assert.h>
#include<windows.h>
char* my_strcat(char* x, char* y)
{
assert(x);
assert(y);
char* p2 = x;
while (*x != '\0')
{
x++;
}
while (*y != '\0')
{
*x++ = *y++;
}
*x = *y;
return p2;
}
int main()
{
char p[64] = "hello";
char* p1 = "world";
my_strcat(p, p1);
system("pause");
return 0;
}
模拟strstr
#include<stdio.h>
#include<assert.h>
#include<windows.h>
char* my_strstr(const char* x, const char* y)
{
assert(x);
assert(y);
char* x1 = NULL;
char* y1 = NULL;
char* p = NULL;
while (*x !='\0')
{
x1 = x;
y1 = y;
while ((*x1 != '\0') && (*y1 != '\0') && (*x1 == *y1))
{
x1++;
y1++;
}
if (*y1 == '\0')
{
return x;
}
x++;
}
return NULL;
}
int main()
{
const char* p = "abcdabcdehij";
const char* p1 = "abcde";
const char* p2 = my_strstr(p, p1);
printf("%s", p2);
system("pause");
return 0;
}
模拟strchr
#include<stdio.h>
#include<windows.h>
#include<assert.h>
char *my_strchr(char *x, char y)
{
assert(x);
while (*x != '\0')
{
if (*x == y)
{
return x;
}
x++;
}
return NULL;
}
int main()
{
char *p = "helloworld";
char ch = 'd';
char *p1 = my_strchr(p, ch);
system("pause");
return 0;
}
模拟strcmp
#include<stdio.h>
#include<assert.h>
#include<windows.h>
int my_strcmp(char* x, char* y)
{
assert(x);
assert(y);
int ret = 0;
while (*x != '\0'&&*y != '\0')
{
if (*x == *y)
{
x++;
y++;
}
else if (*x > *y)
{
ret = 1;
}
else
ret = -1;
}
if ((*x == '\0') && (*y == '\0'))
{
ret = 0;
}
else if (*x == '\0')
{
ret = -1;
}
else
{
ret = 1;
}
return ret;
}
int main()
{
char* p = "hello";
char* p1 = "helloo";
printf("%d", my_strcmp(p, p1));
system("pause");
return 0;
}
模拟memcpy
#include<stdio.h>
#include<assert.h>
#include<windows.h>
void *my_memcpy(void *x, const void *y, int size )
{
assert(x);
assert(y);
char *x1 = (char *)x;
const char* y1 = (const char*)y;
while (size--)
{
*x1++ = *y1++;
}
return x;
}
int main()
{
char a[10] = { 0 };
const char b[] = { 1,2,5,8,3,4,6,8,7 };
int size = sizeof(b) / sizeof(b[0]);
my_memcpy(a, b,size);
system("pause");
return 0;
}
模拟memmove
#include<stdio.h>
#include<windows.h>
#include<assert.h>
#include<string.h>
void *my_memmove(void *dst, const void *src, int size)
{
void *ret = dst;
if (((char*)src<(char*)dst) && (char*)src+size>(char *)dst)
{
src = (char*)src + size - 1;
dst = (char*)src + size - 1;
while (size--)
{
*(char*)dst = *(char*)src;
dst = (char*)dst - 1;
src = (char*)src - 1;
}
}
else
{
while (size--)
{
*(char*)dst = *(char*)src;
dst = (char*)dst + 1;
src = (char*)src + 1;
}
return ret;
}
}
int main()
{
const char buf[32] = "abcd1234";
char buf1[32] = { 0 };
int size = strlen(buf);
my_memmove(buf1, buf, strlen(buf));
system("pause");
return 0;
}