常用的调用库进行字符串拼接
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char str[128] = "chenlichen";
const char* p = "handsome";
char* p2 =(char*)malloc(strlen(p) + strlen(str) + 1);
strcpy(p2, str);
strcat(p2, p);
puts(p2);
free(p2);
return 0;
}
自己写一个字符串拼接函数
char* myStrcat(char* des, char* src)
{
assert(des != NULL && src != NULL);
char* bak = des;
while (*des!='\0')
{
des++;
}
while ((*des++ = *src++) != '\0');
*des = '\0';
return bak;
}
GNU C Library对这个函数的实现如下:
char* myStrcat2(char* des, char* src)
{
char* bak = des;
strcpy(des + strlen(des), src);
return bak;
}
OpenBSD对这个函数的实现如下:
char* myStrcat3(char* des, char* src)
{
assert(des != NULL && src != NULL);
char* bak = des;
for (; *des != '\0'; des++);
while ((*des++ = *src++) != '\0');
*des = '\0';
return bak;
}
主函数
int main()
{
char str[128] = "chenlichen";
char* p = (char*)"handsome";
char* p2;
p2 = myStrcat2(str, p);
puts(p2);
return 0;
}