C语言学习系列2-字符串拼接示例

C语言学习系列2-字符串拼接示例

操作环境:CentOS release 6.4 (Final)
编译环境:gcc (GCC) 4.4.7 20120313 (Red Hat 4.4.7-3)

新建文件helloworld2.c,编辑保存如下内容:

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

/*字符串拼接函数(调用C库函数),*/ 
/*特别注意 join3方法需要放置到main函数之前 ,如果不放在前面则声明也可以*/ 
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;  
} 

int main()
{
    printf("hello world!\n");
    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;  
}

编译文件helloworld2.c
gcc helloworld2.c -o helloworld2

执行查看效果
[root@mail temp]# ./helloworld2
hello world!

/* 使用声明方式代码块如下 */
#include<stdio.h>  
#include<stdlib.h>  
#include<string.h>  

char* join3(char *s1, char *s2) ;

int main()
{
    printf("hello world!\n");
    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;  
}


/*方法三,调用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;  
} 
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值