天天看點

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;

    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://blog.csdn.net/wusuopubupt/article/details/17284423