C语言中的strcat的模拟实现
strcat是字符串追加,可以在目标字符串后加上源字符串
char *strcat(char *Destination,const char *Source);
我们来模拟实现一下
#include<stdio.h>
#include<assert.h>
char* my_strcat(char* Destination,const char* Source)
{
assert(Destination && Source); //断言防止空指针
char* ret = Destination; //保留初始地址,方便返回值
while (*Destination++); //先找到'\0',但由于判断逻辑,Destination在\0的位置还会自增一次
Destination--; //把自增的一次减回去,防止打印结果在\0中断
while (*Destination++ = *Source++);//追加赋值
return ret; //返回起始地址
}
int main()
{
char arr[20] = {"hello "};
printf("%s\n",my_strcat(arr,"world"));
return 0;
}
//当然这么写为了短看起来有些奇怪(甚至还要自减一次),最好换用正常一点的写法,而且这样写可读性差,它不能自己拷贝自己

浙公网安备 33010602011771号