1.模拟实现strncpy
int Mystrncmp(const char *str1,const char*str2,int n)
{
int i = 0;
assert(str1 != NULL && str2 != NULL);
while ((*str1 != 0 || *str2 != 0)&&i++<n)
{
if (*str1 > *str2)
return 1;
else if (*str1 < *str2)
return -1;
str1++;
str2++;
}
return 0;
}
int main()
{
char* str1 = "aacdef";
char* str2 = "abdef";
printf("%d", Mystrncmp(str1, str2, 2));
system("pause");
return 0;
}
2.模拟实现strncat
char *Mystrncat(char *str, const char *src, int n)
{
char *p = str;
int i = 0;
assert(str != NULL&&src != NULL);
while (*str++ != 0);
for (i = 0; i < n; i++)
{
*(str-1) = *src;
str++;
src++;
}
return p;
}
int main()
{
char str[10] = "abcd";
char *src = "hello";
printf("%s",Mystrncat(str, src, 2));
system("pause");
return 0;
}
3.模拟实现strncmp
char *MyStrncmp(char *dest, const char*src, int n)
{
int i = 0;
char *p = dest;
assert(dest != NULL && src != NULL);
for (i = 0; i < n; i++)
{
*dest = *src;
dest++;
src++;
}
return p;
}
int main()
{
char dest[20] = "abcd";
char *src= "hello";
printf("%s\n",MyStrncmp(dest,src,2));
system("pause");
return 0;
}