C語言之strcat函式
阿新 • • 發佈:2019-01-30
【FROM MSDN && 百科】
原型:char *strcat(char *dest,const char *src);
#include<string.h>
Append a string.
把src所指字串新增到dest結尾處(覆蓋dest結尾處的'\0')並新增'\0'。src和dest所指記憶體區域不可以重疊且dest必須有足夠的空間來容納src的字串。
返回指向dest的指標。
DEMO1:實現自己的strcat函式
#include <stdio.h> #include <conio.h> #include <assert.h> char *my_strcat(char *dest,const char *src) //將源字串加const,表明其為輸入引數 { char *strDest=dest; assert(dest!=NULL && src!=NULL); //對源地址和目的地址加非0斷言 //here //若使用while(*Dest++),則會出錯,指向'\0'之後,會出現dest++,則指向了個'\0'的下一個位置, while(*dest !='\0') { dest++; //迴圈體內的++可以使指向字串結束標誌'\0' } while((*dest++=*src++)!='\0'); return strDest; ////為了實現鏈式操作,將目的地址返回 } int main(void) { char str1[20]="hello"; // sufficent space char str2[]=" world"; my_strcat(str1,str2); printf("%s\n",str1); getch(); return 0; }
DEMO2: strcpy && strcat
結果輸出:string = Hello world from strcpy and strcat!#include <stdio.h> #include <conio.h> /*strcpy && strcat*/ int main(void) { char string[80]; strcpy(string,"Hello world from "); strcat(string,"strcpy "); strcat(string,"and "); strcat(string,"strcat!"); printf("string = %s \n",string); getch(); return 0; }
DEMO3:str1 + str2 =str3
#include <stdio.h> #include <conio.h> #include <assert.h> #include <string.h> #include <malloc.h> #pragma warning (disable:4996) int main(void) { char *str1="Welcome ! "; char *str2="Hello,world!"; char *str3; str3=(char*)malloc(strlen(str1)+strlen(str2)+1); //申請空間 //assert(str3); if (str3 == NULL) { fprintf(stderr,"malloc failed......!\n"); } strcpy(str3,str1); //拷貝 strcat(str3,str2); //appending printf("str1 is %s\n",str1); printf("str2 is %s\n",str2); printf("str1 + str2 is %s\n",str3); free(str3); //malloc的記憶體記得要free掉 getch(); return 0; }