模拟实现长度受限制的字符串函数(strncpy、strncat、strncmp)

时间:2023-01-04 08:08:33

根据以上可知,在有的情况下,长度不受限制的字符串函数已经不能满足我们的需求,因此,便需要一些长度受限制的字符串函数,来满足我们的需要。
长度受限制的字符串函数,可以根据我们的需求,给指定的长度,从而完成我们的需求。
先看这些函数的原型:

char *strncat( char *strDest, const char *strSource, size_t count );
int strncmp( const char *string1, const char *string2, size_t count );
char *strncpy( char *strDest, const char *strSource, size_t count );

根据以上原型,现在模拟实现这些函数,从而加强对这些函数的理解。

**//strncat字符串追加**
char *my_strncat(char *pdest, const char *pstr, size_t n)
{
assert(pdest!= NULL);
assert(pstr != NULL);
char *ret = pdest;
while (*pdest != '\0')//找目标空间的'\0'
{
pdest++;
}
while ((*pstr != '\0') && (n-->0))//拷贝字符串到目标空间
{
*pdest = *pstr;
*pdest++;
*pstr++;
}
if (n-- < 0)
{
*pdest = 0;
}
return ret;
}
int main()
{
char arr[20] = "hello ";
char*p = "world";
my_strncat(arr, p,6);
printf("%s\n", arr);
system("pause");
return 0;
}
**//模拟实现strncmp(字符串比较)**
int my_strncmp(const char *string1, const char *string2, size_t n)
{
assert(string1 != NULL);
assert(string2 != NULL);
while ((*string1 == *string2) && (n-- >= 0))
{
string1++;//如果相等,则一直向后比较
string2++;
}
if ((*string1 != *string2))
{
return *string1 - *string2;
}
//如果两者不相等,则利用ascll值返回
}
int main()
{
char *arr1 = "abcdef";
char *arr2 = "abchdz";
int ret = my_strncmp(arr1, arr2,3);
printf("%d\n", ret);
system("pause");
return 0;
}
**//模拟实现strncpy(字符串拷贝)**
char*my_strncpy(char* pdest, const char*psrc,size_t n)
{
char *ret = pdest;
assert(pdest);
assert(psrc);
while ((*psrc != NULL) && n-->0)
{
*pdest = *psrc;
pdest++;
psrc++;
}
if (*psrc != NULL)
{
*pdest = 0;
}
return ret;
}
int main()
{
int *arr = "abcdef";
int buf[20] = { 0 };
my_strncpy(buf, arr,2);
printf("%s\n", buf);
system("pause");
return 0;
}

模拟实现库函数,不仅有利于我们对这些函数的理解,更有利用我们今后的学习。