3 ways to connect a C-language string
#include <stdio.h>#include<stdlib.h>#include<string.h>Char*join1 (Char*,Char*);voidJoin2 (Char*,Char*);Char*join3 (Char*,Char*);intMainvoid) { Chara[4] ="ABC";//char *a = "ABC" Charb[4] ="def";//char *b = "Def" Char*c =Join3 (A, b); printf ("concatenated String is%s\n", c); Free (c); C=NULL; return 0;}/*method One, does not change the string, a, B, through malloc, generates a third string C, which returns a local pointer variable*/Char*join1 (Char*a,Char*b) {Char*c = (Char*) malloc (strlen (a) + strlen (b) +1);//local variables, requesting memory with malloc if(c = = NULL) exit (1); Char*TEMPC = C;//Save the first address . while(*a! =' /') { *c++ = *a++; } while((*c++ = *b++)! =' /') { ; } //Notice that at this point the pointer C has pointed to the end of the string after stitching! returnTEMPC;//The return value is a pointer variable for the local malloc request, which is required at the end of the function call.}/*method Two, change the string a directly,*/voidJoin2 (Char*a,Char*b) {//Note that if a, B in the main function defines a string constant (as follows)://char *a = "abc"; //char *b = "Def"; //then the join2 is not workable. //This must be defined://char a[4] = "ABC"; //char b[4] = "def"; while(*a! =' /') {a++; } while((*a++ = *b++)! =' /') { ; }}/*method Three, call C library function,*/Char* JOIN3 (Char*S1,Char*S2) { Char*result = malloc (strlen (S1) +strlen (S2) +1);//+1 for the Zero-terminator//In the real code you would check for errors in malloc here if(Result = = NULL) exit (1); strcpy (result, S1); strcat (result, S2); returnresult;}
Transferred from: http://blog.csdn.net/wusuopubupt/article/details/17284423
3 ways to connect a C-language string