1.模拟实现strncpy
//1.模拟实现strncpy
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
char * mystrncpy(char * dest, const char * sour, int num)
{
char *p = dest;
char *q = sour;
assert(dest != NULL);
assert(sour != NULL);
while (num!=0)
{
if (*q!="\0")
{
*p = *q;
p++;
q++;
}
else
{
break;
}
num--;
}
return dest;
}
int main()
{
char arr1[] = "hello future";
char arr2[20] = { 0 };
printf("%s\n", mystrncpy(arr2, arr1, 10));
system("pause");
return 0;
}
2.模拟实现strncat
//2.模拟实现strncat
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
char * mystrncat(char * dest, const char * sour, int num)
{
char *ret = dest;
assert(dest != NULL);
assert(sour != NULL);
while (*dest)
{
dest++;
}
while (num && (*dest++ = *sour++) != 0)
{
num--;
}
return ret;
}
int main()
{
char arr1[30] = "To be ";
char arr2[20] = "or not to be!!!";
printf("%s\n", mystrncat(arr1, arr2, 13));
system("pause");
return 0;
}
3.模拟实现strncmp
//3.模拟实现strncmp
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
int mystrncmp(const char *s1, const char *s2, size_t len)
{
//判断str1与str2指针是否为NULL
assert(s1 != NULL && s2 != NULL);
while (len--)
{
if (*s1 == 0 || *s1 != *s2)
{
return *s1 - *s2;
}
s1++;
s2++;
}
return 0;
}
int main()
{
char arr1[] = "abcdeg";
char arr2[] = "abcdfg";
int tem = mystrncmp(arr1, arr2,5);//1: arr1大 返回1 2: arr2大 返回-1 3: 相等 返回0
printf("%d\n", tem);
if (tem==1)
{
printf("arr1>arr2");
}
else if (tem==-1)
{
printf("arr1<arr2");
}
else if (tem == 0)
{
printf("arr1=arr2");
}
system("pause");
return 0;
}