模拟实现C库函数strcpy,strcat,strstr,strchr,strcmp,memcpy,memmove

时间:2022-12-27 17:01:35

1、模拟实现strcpy

char *my_strcpy( char *dest, const char *str)
{
assert(dest != NULL);
assert(str != NULL);
while (*dest++=*str++)
{
;
}
return dest;
}
int main()
{
char p[20];
char *p1 = "world";
my_strcpy(p, p1);
printf("%s\n", p);
system("pause");
return 0;
}

2、模拟实现strcat

char* my_strcat(char*dest, const char* str)
{
assert(dest != NULL);
assert(str != NULL);
char *ret = dest;
while (*dest)
{
dest++;
}
while (*str)
{
*dest++ = *str++;
}
return ret;
}
int main()
{
char p[20] = "hello ";
my_strcat(p, "world");
printf("%s", p);
system("pause");
return 0;
}


3、模拟实现strstr

char* my_strstr(const char *dest, const char*str)
{
assert(dest != NULL);
assert(str != NULL);
char *ret = (char*)dest;
char *cur = (char*)str;
while (*cur)
{
if ((*ret) && (*cur) && (*ret++ = *cur++))
{
return cur;
}
cur++;
}
return NULL;
}

int main()
{
char p[] = "abcdefd";
char* p1 = "defr";
char* ret = NULL;
ret= strstr(p, p1);
if (ret == NULL)
{
printf("no");
}
else
{
printf("%s", ret);
}
system("pause");
}

4、模拟实现strchr

char* my_strchr(const char*dest, int x)
{
assert(dest != NULL);
char*ret = (char*)dest;
while (*ret)
{
if ((*ret) && (*ret == x))
{
return ret;
}
ret++;
}
return NULL;
}

int main()
{
char p[] = "abcdefg";
char*ret=my_strchr(p, 'f');
if (ret == NULL)
{
printf("no\n");
}
else
{
printf("%s", ret);
}
system("pause");

}
5、模拟实现strcmp

int my_strcmp(const char*str1, const char*str2)
{
assert(str1 != NULL);
assert(str2 != NULL);
while (*str1==*str2)
{
if (*str1 == '\0')
{
return 0;
}
*str1++;
*str2++;
}
if (*str1 > *str2)
{
return 1;
}
else if (*str1 < *str2)
{
return -1;
}
}

int main()
{
char p1[] = "dccbcc";
char p2[] = "dccccc";
int ret = my_strcmp(p1, p2);
printf("%d\n", ret);
system("pause");
}

6、模拟实现memcpy

void*my_memcpy(void*dest, const void*str, size_t sz)
{
assert(dest != NULL);
assert(str != NULL);
char* ret = (char*)str;
char* cur = (char*)dest;
while (sz--)
{
*cur++ = *ret++;
}
return dest;
}

int main()
{
char p1[20] = { 0 };
char* p2 = "world";
my_memcpy(p1, p2, 4);
printf("%s\n", p1);
system("pause");
return 0;
}

7、模拟实现memmove

void* my_memmove(void*dest, const void*str, size_t len)
{
assert(dest != NULL);
assert(str != NULL);
char *pdest = (char*)dest;
char* pstr = (char*)str;
if ((pstr < pdest) && (pdest < pstr + len))
{
while (len--)
{
*(pdest+len) = *(pstr+len);
}
}
else
{
while (len--)
{
*pdest++ = *pstr++;
}
}
return dest;
}
int main()
{
char p[] = "abcdefgh";
my_memmove(p, p+2, 4);
printf("%s", p);
system("pause");
return 0;
}