模拟实现strncpy,strncat,strncmp

时间:2023-12-11 17:24:44
1.模拟实现strncpy 
<1.>strncpy相比于strcpy增加了size_t参数可以实现最多拷贝的字节数
<2.>(size_t不可以超出拷贝存放的内存大小)来保证不会超出destanaton的内存,
<3.>但是需要注意的是,如果你需要拷贝的长度小于源字符串长度,那么strncpy不会在末尾加'\0'
 #include<stdio.h>
#include<assert.h>
#include<string.h>
char* Strncpy(char* destination, const char* source, size_t num)
{
size_t i = ;
while (i<num)
{
destination[i] = source[i];
++i;
}
return destination;
}
int main()
{
char str1[] = "To be or not to be";
char str2[];
char str3[];
//拷贝最大的字节
Strncpy(str2, str1, sizeof(str2));
//拷贝小于str1的字节
Strncpy(str3, str2, );
str3[] = '\0'; //需要自己加如'\0'
puts(str1);
puts(str2);
puts(str3);
return ;
}
2.模拟实现strncat
<1.>现在destination函数中找到'\0',然后将source函数中的num个字符拼接到destination中
<2.>注意source函数不能修改,需要加const
<3.>返回结果是指针类型
 #include<stdio.h>
#include<assert.h>
char* Strncat(char* destination, const char* source, size_t num)
{
//检查合法性
assert(destination != NULL);
assert(source != NULL);
//找到destination中的'\0'
int i = ;
while (destination[i]!='\0')
{
i++;
}
//拼接字符串
for (int j = ; num > ; i++, j++, num--)
{
destination[i] = source[j];
}
destination[i] = '\0';
return destination;
}
int main()
{
char str1[] = "abcd";
char str2[] = "efghijklmn";
//拼接前4个字符
Strncat(str1,str2,);
puts(str1);
printf("\n");
//拼接全部字符,(因为上一个Strncat已经改变了str1的值)
Strncat(str1, str2, sizeof(str2));
puts(str1);
return ;
}
3.模拟实现strncmp
<1.>strncmp返回值与strcmp一样
<2.>如果str1与str2前num个字符一样则返回0
<3.>str1小于str2则返回一个小于0的数
<4.>str1大于str2则返回一个大于0的数
 #include <stdio.h>
#include<assert.h>
#include<string.h>
int Strncmp(const char* str1, const char* str2, size_t num)
{
assert(str1 != NULL);
assert(str2 != NULL);
while (num>)
{
if (*str1 > *str2)
{
return ;
}
else if (*str1 < *str2)
{
return -;
}
else if (*str1 == *str2)
{
str1++;
str2++;
num--;
}
else
{
str1++;
str2++;
num--;
}
}
return ;
}
int main()
{
char str1[] = "abcdef";
char str2[] = "abty";
//模拟实现Strncmp
printf("%d\n", Strncmp(str1, str2, ));//前两个字符相等
printf("%d\n", Strncmp(str1, str2, ));//前三个字符不相等
printf("%d\n", Strncmp("abcde", "abc", ));//str1大于str2
printf("%d\n", Strncmp("abc", "abcde", ));//str1小于str2
printf("\n");
//库函数strncmp
printf("%d\n", strncmp(str1, str2, ));
printf("%d\n", strncmp(str1, str2, ));
printf("%d\n", strncmp("abcde", "abc", ));
printf("%d\n", strncmp("abc", "abcde", ));
return ;
}