生活随笔
收集整理的這篇文章主要介紹了
【C语言学习笔记】字符串拼接的3种方法 .
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
昨天晚上和@buptpatriot討論函數返回指針(malloc生成的)的問題,提到字符串拼接,做個總結。
?
?
[cpp] view plaincopyprint?
#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?b[4]?=?"def";???????char?*c?=?join3(a,?b);??????printf("Concatenated?String?is?%s\n",?c);????????free(c);??????c?=?NULL;????????return?0;??}????char?*join1(char?*a,?char?*b)?{??????char?*c?=?(char?*)?malloc(strlen(a)?+?strlen(b)?+?1);?????if?(c?==?NULL)?exit?(1);??????char?*tempc?=?c;?????while?(*a?!=?'\0')?{??????????*c++?=?*a++;??????}??????while?((*c++?=?*b++)?!=?'\0')?{??????????;??????}??????????return?tempc;}??????void?join2(char?*a,?char?*b)?{??????????????????????????????????while?(*a?!=?'\0')?{??????????a++;??????}??????while?((*a++?=?*b++)?!=?'\0')?{??????????;??????}??}????char*?join3(char?*s1,?char?*s2)??{??????char?*result?=?malloc(strlen(s1)+strlen(s2)+1);????????if?(result?==?NULL)?exit?(1);????????strcpy(result,?s1);??????strcat(result,?s2);????????return?result;??}??
轉載于:https://www.cnblogs.com/wangluochong/p/4169727.html
總結
以上是生活随笔為你收集整理的【C语言学习笔记】字符串拼接的3种方法 .的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。