1.模拟实现strncpy
strncpy函数用于将指定长度的字符串复制到字符数组中,
是 C语言的库函数之一,定义于 string.h。
语法形式为:
char * strncpy(char * destination,const char *scource,size_t num)
表示把src所指向的字符串中以src地址开始的前n个字节复制到dest所指的数组中,并返回被复制后的dest。
把source指向的字符串的前size_t n个字符(不包括\0,\0得自己手动加在*des
被复制之后)复制到des指向的字符串中。
如果要复制的source的部分有\0,就把\0复制进去,之后就提前结束,即使没复制到第size_t n个字符也是。返回指向destin的指针。
#include<stdio.h>
#include<Windows.h>
//#include<string.h>
#include<assert.h>
#pragma warning (disable:4996)
void My_strncpy(char *des, char *scr, int num)
{
assert(des != NULL);
assert(scr != NULL);
while (num && (*des++ = *scr++))
{
num--;
}
if (num > 0)
{
des == NULL;//源字符串小于num,手动增加NULL
}
}
int main()
{
char str1[] = "i am a student";
char str2[20] = { 0 };
//strncpy(str2, str1, 6);
My_strncpy(str2, str1, 6);
printf("%s", str2);
system("pause");
return 0;
}
2.模拟实现strncat
strncat()主要功能是在字符串的结尾追加n个字符
把src所指字符串的前n个字符添加到dest所指字符串的结尾处,并覆盖dest所指字符串结尾的’\0’,从而实现字符串的连接,再追加’\0’。
说明:src和dest所指内存区域不可以重叠,并且dest必须有足够的空间来容纳src的字符串。
char * strncat(char *dest, const char *src, size_t n);
#include<stdio.h>
#include<Windows.h>
//#include<string.h>
#include<assert.h>
#pragma warning (disable:4996)
voi
void My_strncat(char *des,char *scr,int num)
{
assert(des != NULL);
assert(scr != NULL);
while (*des)
{
*des++;
}//找到目标字符串的'\0',开始拷贝
while (num&&(*des++ = *scr++))
{
num--;
}
des = NULL;
}
int main()
{
char str1[] = "i am a student";
char str2[20] = { "fgys"};
strncat(str2, str1, 6);
My_strncat(str2, str1, 6);
printf("%s", str2);
system("pause");
return 0;
}
3.模拟实现strncmp
strncmp函数为字符串比价函数,
字符串大小的比较是以ASCII 码表上的顺序来决定,此顺序亦为字符的值。
其函数声明为
int strncmp ( const char * str1, const char * str2, size_t n );
功能是把 str1 和 str2 进行比较,最多比较前 n 个字节,
若str1与str2的前n个字符相同,则返回0;
若s1大于s2,则返回大于0的值;
若s1 小于s2,则返回小于0的值;
#include<stdio.h>
#include<Windows.h>
#include<assert.h>
#pragma warning (disable:4996)
int My_strncmp(char *des, char *scr, int num)
{
int ret = 0;
assert(des != NULL);
assert(scr != NULL);
while ((*scr == *des) && num)
{
if (*des == '\0')
{
return 0;
}
scr++;
des++;
}
return *des - *scr;
}
int main()
{
char str1[] = "i am a student";
char str2[20] = { "fgys"};
int res = My_strncmp(str1, str2, 6);
if (res > 0)
{
printf("str1>srt2");
}
else if (res < 0)
{
printf("str1<str2");
}
else{
printf("str1=str2");
}
system("pause");
return 0;
}