首页 > 编程语言 > 详细

C语言实现字符串拼接

时间:2015-10-16 17:07:23      阅读:349      评论:0      收藏:0      [点我收藏+]

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char* str_contact(const char*,const char*);

/**
** C语言实现字符串拼接
**/
int main(void)
{
char *ch1 = "hui_";
char *ch2 = "_heihei";
char *res = NULL;
res = str_contact(ch1,ch2);
printf("res = %s\n",res);
free(res);
res = NULL;
}

/**
** 字符串拼接方法
**/
char * str_contact(const char *str1,const char *str2)
{
char * result;
result = (char*)malloc(strlen(str1) + strlen(str2) + 1); //str1的长度 + str2的长度 + \0;
if(!result){ //如果内存动态分配失败
printf("Error: malloc failed in concat! \n");
exit(EXIT_FAILURE);
}
strcpy(result,str1);
strcat(result,str2); //字符串拼接
return result;
}

C语言实现字符串拼接

原文:http://www.cnblogs.com/xiaohuihui123/p/4885625.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!