【C语言学习笔记】字符串拼接的3种方法

57 篇文章 3 订阅

昨天晚上和@buptpatriot讨论函数返回指针(malloc生成的)的问题,提到字符串拼接,做个总结。


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

char *join1(char *, char*);
void join2(char *, char *);
char *join3(char *, char*);

int main(void) {
	char a[4] = "abc"; // char *a = "abc"
	char b[4] = "def"; // char *b = "def"

	char *c = join3(a, b);
	printf("Concatenated String is %s\n", c);

	free(c);
	c = NULL;

	return 0;
}

/*方法一,不改变字符串a,b, 通过malloc,生成第三个字符串c, 返回局部指针变量*/
char *join1(char *a, char *b) {
	char *c = (char *) malloc(strlen(a) + strlen(b) + 1); //局部变量,用malloc申请内存
	if (c == NULL) exit (1);
	char *tempc = c; //把首地址存下来
	while (*a != '\0') {
		*c++ = *a++;
	}
	while ((*c++ = *b++) != '\0') {
		;
	}
	//注意,此时指针c已经指向拼接之后的字符串的结尾'\0' !
	return tempc;//返回值是局部malloc申请的指针变量,需在函数调用结束后free之
}


/*方法二,直接改掉字符串a, 此方法有误,见留言板*/
void join2(char *a, char *b) {
	//注意,如果在main函数里a,b定义的是字符串常量(如下):
	//char *a = "abc";
	//char *b = "def";
	//那么join2是行不通的。
	//必须这样定义:
	//char a[4] = "abc";
	//char b[4] = "def";
	while (*a != '\0') {
		a++;
	}
	while ((*a++ = *b++) != '\0') {
		;
	}
}

/*方法三,调用C库函数,*/
char* join3(char *s1, char *s2)
{
    char *result = malloc(strlen(s1)+strlen(s2)+1);//+1 for the zero-terminator
    //in real code you would check for errors in malloc here
	if (result == NULL) exit (1);

    strcpy(result, s1);
    strcat(result, s2);

    return result;
}



参考: http://stackoverflow.com/questions/8465006/how-to-concatenate-2-strings-in-c

           http://www.cplusplus.com/reference/cstdlib/malloc/

           http://www.programmingspark.com/2012/02/c-program-to-concatenate-two-strings.html


update

---------

留言中,@napoleon_1815 同学说的很对,我的join2方法是不对的,谢谢同学指正!

  • 17
    点赞
  • 64
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值