C语⾔字符串连接的3种⽅式C 语⾔字符串连接的 3种⽅式
#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;
return0;
}
/*⽅法⼀,不改变字符串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;
molloc函数
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。