关于C语言字符串拼接的几个方法!

2019-07-25 15:01发布

本帖最后由 dirtwillfly 于 2015-9-21 08:34 编辑

字符串拼接的3种方法
1
  • #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 ", 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 != '') {  
  •         *c++ = *a++;  
  •     }  
  •     while ((*c++ = *b++) != '') {  
  •         ;  
  •     }  
  •     //注意,此时指针c已经指向拼接之后的字符串的结尾'' !  
  •     return tempc;//返回值是局部malloc申请的指针变量,需在函数调用结束后free之  
  • }  
友情提示: 此问题已得到解决,问题已经关闭,关闭后问题禁止继续编辑,回答。
该问题目前已经被作者或者管理员关闭, 无法添加新回复
5条回答
東南博士
1楼-- · 2019-07-25 20:05
/*方法二,直接改掉字符串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 != '') {  
        a++;  
    }  
    while ((*a++ = *b++) != '') {  
        ;  
    }  
}  
東南博士
2楼-- · 2019-07-25 23:19
/*方法三,调用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;  
}  
zhangbo1985
3楼-- · 2019-07-26 00:57
这三个函数简洁易用,值得推广。
dirtwillfly
4楼-- · 2019-07-26 02:41
 精彩回答 2  元偷偷看……
東南博士
5楼-- · 2019-07-26 08:31
简洁易用,尤其是是串口解析的时候。

一周热门 更多>