//求字符串长度的函数
int my_strlen(const char* pStr)
{
assert(pStr != NULL);
int length = 0;
while (*pStr++ != ‘\0‘)
{
length++;
}
return length;
}
//字符串拷贝函数
char* my_strcpy(char* strDest, const char* strSrc)
{
assert(strDest != NULL && strSrc != NULL);
char* pDest = strDest; //保护参数
const char* pSrc = strSrc;
while (*pSrc != ‘\0‘)
{
*pDest++ = *pSrc++;
}
//*pDest = ‘\0‘;
return strDest;
}
//字符串比较函数
int my_strcmp(const char* strDest, const char* strSrc)
{
assert(strDest != NULL && strSrc != NULL);
if (*strDest == ‘\0‘&&*strSrc != ‘\0‘)
{
return 0;
}
const char* pDest = strDest;
const char* pSrc = strSrc;
int result = 0; //用于记录比较结果
while (*pDest != ‘\0‘ || *pSrc != ‘\0‘)
{
if ((result = *pDest - *pSrc) != 0)
{
break;
}
pDest++;
pSrc++;
}
if (result > 0)
{
result = 1;
}
else if (result<0)
{
result = -1;
}
return result;
}
//字符串连接函数
char* my_strcat(char* strDest, char* strSrc)
{
assert(strDest != NULL && strSrc != NULL);
char* pDest = strDest;
char* pSrc = strSrc;
while(*pDest != ‘\0‘)
{
pDest++;
}
while (*pSrc != ‘\0‘)
{
*pDest++ = *pSrc++;
}
*pDest = ‘\0‘;
return strDest;
}
/内存比较函数
int my_memcmp(void* src1, void* src2, int len)
{
assert(src1 != NULL && src2 != NULL);
const char* pSrc1 = (char*)src1;
const char* pSrc2 = (char*)src2;
while (len-- > 0)
{
if (*pSrc1++ != *pSrc2++)
{
return *pSrc1 < *pSrc2 ? -1 : 1;
}
}
return 0;
}
//内存拷贝函数
void* my_memcpy(void* dest, const void* src, size_t count)
{
assert(dest != NULL && src != NULL);
char* pDest = (char*)dest;
const char* pSrc = (const char*)src;
while (count-- > 0)
{
*pDest++ = *pSrc++;
}
return dest;
}
//内存移动函数
void* my_memmove(void* dest, void* src, size_t count)
{
assert(dest != NULL && src != NULL);
char* pDest = (char*)dest;
const char* pSrc = (char*)src;
if (pSrc >= pDest || pDest >= (pSrc + count))
{
while (count-- > 0)
{
*pDest++ = *pSrc;
}
}
else
{
while (count-- > 0)
{
*(pDest + count) = *(pSrc + count);
}
}
*pDest = ‘\0‘;
return dest;
}