1.模拟实现strncpy
char *my_strncpy(char *dest, const char* str, int count)
{
assert(dest != NULL);
assert(str != NULL);
char *ret = dest;
while (count && (*dest++ = *str++))
{
count--;
}
if (count>0)
{
while (--count)
{
*dest++ = '\0';
}
}
return ret;
}
int main()
{
char arr[10];
my_strncpy(arr, "hello", 3);
printf("%s\n", arr);
system("pause");
return 0;
}
2.模拟实现strncat
char *my_strncat(char*dest, const char*str, int count)
{
assert(dest != NULL);
assert(str != NULL);
char *ret = dest;
while (*dest)
{
dest++;
}
while (count && (*dest++ = *str++))
{
count--;
}
if (count > 0)
{
while (--count)
{
*dest++ = '\0';
}
}
return ret;
}
int main()
{
char arr1[20]="hello ";
char arr2[] = "world";
my_strncat(arr1, arr2, 7);
printf("%s\n", arr1);
system("pause");
return 0;
}
3.模拟实现strncmp
strcmp函数原型:int strncmp ( const char * str1, const char * str2, size_t n );
若str1与str2的前n个字符相同,则返回0;若s1大于s2,则返回大于0的值;若s1 若小于s2,则返回小于0的值
strncmp()首先将s1 第一个字符值减去s2 第一个字符值,若差值为0 则再继续比较下个字符,直到字符结束标志'\0',若差值不为0,则将差值返回。
int my_strncmp(const char*str1,const char*str2,int count)
{
assert(str1 != NULL);
assert(str2 != NULL);
int ret;
while (count&&*str1&&*str2)
{
if (*str1 == *str2)
{
ret = 0;
str1++;
str2++;
}
else if (*str1 > *str2)
{
ret = 1;
break;
}
else if (*str1 < *str2)
{
ret = -1;
break;
}
count--;
}
return ret;
}
int main()
{
char arr1[] = "hekkk";
char arr2[] = "hekkk";
int ret=my_strncmp(arr1, arr2, 6);
printf("%d\n", ret);
system("pause");
return 0;
}