函数strncpy,strncat,strncmp的使用以及模拟实现
strncpy
拷贝num个字符从源字符串到目标空间
如果源字符串的长度小于num,则拷贝完源字符串之后,在目标的后边追加0,直到num个
int main()
{
char arr[] = "xxxxxxxx";
char arr1[] = "abcdef";
strncpy(arr, arr1, 7);
printf("%s\n", arr);
return 0;
}
模拟实现strncpy
char* my_strncpy(char* des, const char* src, size_t num)
{
assert(des && src);
char* ps = des;
while (num--)
{
//防止指针越界
if (*src == '\0')
{
*des++ = '\0';
}
else
*des++ = *src++;
}
return ps;
}
int main()
{
char arr[] = "xxxxxxxx";
char arr1[] = "abcdef";
my_strncpy(arr, arr1, 7);
printf("%s\n", arr);
return 0;
}
strncat
追加num个字符,从源字符串到目标字符串,追加之后会给目标字符串补个’\0’
如果源字符串的长度小于num,则追加完源字符串之后,只会补一个’\0’
int main()
{
char arr[20] = "hello ";
char arr1[] = "world";
strncat(arr, arr1, 7);
printf("%s\n", arr);
return 0;
}
模拟实现strncat
char* my_strncat(char* des, const char* src, size_t num)
{
assert(des && src);
char* ps = des;
while (*des)
{
des++;
}
while (*des++ = *src++)
;
*des = '\0';
return ps;
}
int main()
{
char arr[20] = "hello ";
char arr1[] = "world";
my_strncat(arr, arr1, 7);
printf("%s\n", arr);
return 0;
}
strncmp
比较到出现到字符不一样或者一个字符串结束或者num个字符串全部比较完
模拟实现strncmp
int my_strcmp(const char* des, const char* src,size_t num)
{
assert(des && src);
while (num--)
{
if (*des == *src)
{
if (*des == '\0')
return 0;
des++;
src++;
}
else if(*des > *src)
{
return 1;
}
else
{
return -1;
}
}
}
int main()
{
char arr[] = "abbedf";
char arr1[] = "abc";
int ret=strncmp(arr, arr1,4);
if (ret > 0)
printf(">\n");
else if (ret < 0)
printf("<\n");
else
printf("==\n");
return 0;
}