文章目录
前言
这是我对库函数的模拟实现,希望对大家有帮助。
一、模拟实现strlen
#include<stdio.h>
#include<assert.h>
size_t my_strlen(const char* str)
{
assert(str);
int tmp = 0;
while (*str)
{
tmp++;
str++;
}
if (!tmp)
return NULL;
return tmp;
}
二、模拟实现strcpy
char* my_strcpy(char* strDestination, const char* strSource)
{
assert(strDestination&& strSource);
char* tmp_strDestination = strDestination;
while (*strDestination++ = *strSource++);
return tmp_strDestination;
}
三、模拟实现strcat
#include<stdio.h>
#include<assert.h>
char* my_strcat(char* strDestination, const char* strSource)
{
assert(strDestination&& strSource);
char* tmp_strDestination = strDestination;
while (*strDestination++);
strDestination--;
while (*strDestination++ = *strSource++);
return tmp_strDestination;
}
四、模拟实现strcmp
#include<stdio.h>
#include<assert.h>
int my_strcmp(const char* string1, const char* string2)
{
assert(string1 && string2);
for (;;string1++, string2++)
{
if (*string1 == *string2 && *string2 == '\0')
return 0;
else if (*string1 == '\0' || *string1 < *string2)
return -1;
else if(*string2 == '\0' || *string1 > *string2)
return 1;
}
}
五、模拟实现strstr
#include<stdio.h>
#include<assert.h>
char* my_strstr(const char* string, const char* strCharSet)
{
assert(string && strCharSet);
char* tmp_string = (char*)string;
if (strCharSet == NULL)
return tmp_string;
while (*tmp_string)
{
char* tmp_s1 = (char*)tmp_string,
* tmp_s2 = (char*)strCharSet;
while (!(*tmp_s1 - *tmp_s2) && *tmp_s1++ && *tmp_s2++);
if (!*tmp_s2)
return tmp_string;
tmp_string++;
}
return NULL;
}
六、模拟实现memcpy
#include<stdio.h>
#include<assert.h>
void* my_memcpy(void* dest, const void* src, size_t count)
{
assert(dest && src);
char* tmp_dest = dest;
while (count--)
*((char*)dest)++ = *((char*)src)++;
return tmp_dest;
}
七、模拟实现memmove
#include<stdio.h>
#include<assert.h>
void* my_memmove(void* dest, const void* src, size_t count)
{
assert(dest && src);
void* tmp_dest = dest;
if (dest < src)
while (count--)
*((char*)dest)++ = *((char*)src)++;
else
while (count--)
*((char*)dest + count) = *((char*)src + count);
return dest;
}