One is to use the strcat function of C language. strcat(str1,str2) can connect the string specified by str2 to the string specified by str1. The result is stored in the specified character array. The original last '\ 0' of the string specified by str1 is cancelled. Because you want to connect str2 to str1, you should allocate more memory to str1.
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char str1[128]={0}; char str2[32]={0}; scanf("%s %s",str1,str2); printf("%s\n",strcat(str1,str2)); printf("\n"); system("pause"); return 0; }
The other is to write a function to connect the string in str2 to str1. I defined three character arrays str1, str2 and str3, where str3 is used to store the contents of str1 and str2.
#include <stdio.h> #include <stdlib.h> #include <string.h> char str3[200];//The length should be greater than the sum of str1+str2 to avoid overflow void connect(char str1[],char str2[]); int main() { char str1[100]; char str2[100]; scanf("%s %s",str1,str2); connect(str1,str2); printf("%s",str3); printf("\n"); system("pause"); return 0; } void connect(char str1[],char str2[]) { int i=0,j=0; while(str1[i]!='\0') { /*str3[j]=str1[i]; i++; j++;*/ str3[j++]=str1[i++]; } i=0; while(str2[i]!='\0') { /*str3[j]=str2[i]; i++; j++;*/ str3[j++]=str2[i++]; } str3[j]='\0'; }
After writing this code, I found that although I connected two strings, I defined an array more, which is a waste of memory, so I optimized it, and connected str2 directly to str1.
#include <stdio.h> #include <stdlib.h> #include <string.h> void connect(char str1[],char str2[]) { int i=0,j=0;//count while(str1[i]!='\0') i++; while(str2[j]!='\0') { str1[i]=str2[j]; i++; j++; //It can also be written as str1[i++]=str2[j + +] } } int main() { char str1[128]={0}; char str2[32]={0}; scanf("%s %s",str1,str2); connect(str1,str2); printf("%s\n",str1); printf("\n"); system("pause"); return 0; }
You can use the strlen function in these codes to see the changes of string length before and after. I will not list them here.