【C語言學習筆記】字串拼接的3種方法

來源:互聯網
上載者:User

昨天晚上和@buptpatriot討論函數返回指標(malloc產生的)的問題,提到字串拼接,做個總結。


#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 hereif (result == NULL) exit (1);    strcpy(result, s1);    strcat(result, s2);    return result;}

參考: http://stackoverflow.com/questions/8465006/how-to-concatenate-2-strings-in-c

           http://www.cplusplus.com/reference/cstdlib/malloc/

           http://www.programmingspark.com/2012/02/c-program-to-concatenate-two-strings.html


update

---------

留言中,@napoleon_1815 同學說的很對,我的join2方法是不對的,謝謝同學指正。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.