為了便於理解和使用庫函數,先把自己實現的幾個函數以及測試函數呈現如下。
//求字符串長度的函數
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'; //庫函數strcpy中是沒有拷貝'\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));
}