自己实现的库函数1(strlen,strcpy,strcmp,strcat)

时间:2022-02-11 16:09:15

为了便于理解和使用库函数,先把自己实现的几个函数以及测试函数呈现如下。

//求字符串长度的函数
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指到字符串末尾
{
pDest++;
}
while (*pSrc != '\0')
{
*pDest++ = *pSrc++;
}
*pDest = '\0';
return strDest;
}
void Test()
{
char c1[5] = "abcd";
char c2[4] = "123";
char c3[20] = "123456";
printf("c1-length:%d\n", my_strlen(c1));
printf("my_strcpy(c1,c2):%s\n", my_strcpy(c1, c2));
//printf("%s\n", my_strcpy(c1, c3)); //不能处理这种超出范围的,程序会崩溃!!
printf("my_strcmp(c1,c2):%d\n", my_strcmp(c1, c2));
printf("my_strcmp(c2,c3):%d\n", my_strcmp(c2, c3));
printf("my_strcat(c3,c2):%s\n",my_strcat(c3,c2));
}