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;
}