-
strcat
鎖定
將兩個char類型連接。
例如:
char d[20]="Golden";
char s[20]="View";
strcat(d,s);
//打印d
printf("%s",d);
輸出 d 為 GoldenView (中間無空格)
d和s所指內存區域不可以重疊且d必須有足夠的空間來容納s的字符串。
返回指向d的指針。
strcatC函數
strcat原型
extern char *strcat(char *dest, const char *src);
strcat用法
#include <string.h>
strcat頭文件
在C中,函數原型存在 <string.h>頭文件中。
在C++中,則存在於<cstring>頭文件中。
strcat功能
把src所指向的字符串(包括“\0”)複製到dest所指向的字符串後面(刪除*dest原來末尾的“\0”)。要保證*dest足夠長,以容納被複制進來的*src。*src中原有的字符不變。返回指向dest的指針。
strcat説明
src和dest所指內存區域不可以重疊且dest必須有足夠的空間來容納src的字符串。
strcat舉例
// strcat.c #include <syslib.h> #include <string.h> main() { char d[20] = "GoldenGlobal"; char* s = "View"; clrscr(); strcat(d,s); printf("%s",d); getchar(); return 0; } // strcat.cpp #include <iostream> #include <cstring> #include <cstdlib> int main() { using namespace std; char d[20] = "GoldenGlobal"; char* s = "View"; system("cls"); strcat(d,s); cout << d << endl; system("pause"); return 0; }
程序執行結果為:
GoldenGlobalView
Strcat函數原型如下(以下代碼為錯誤代碼,想要通過char *指針修改字符串常量中的字符會導致Segment fault錯誤):
/* * 注意以下代碼有問題: * 1. 指針strDest被修改了,實際在使用中並不會去調用返回值來重新獲取strDest原來的值 * 2. 代碼註釋不該這麼寫,函數註釋只需要寫使用方法,無需寫實現過程[所以實現過程儘量保證正確] */ //將源字符串加const,表明其為輸入參數 char* strcat(char* strDest , const char* strSrc) { //後文return address,故不能放在assert斷言之後聲明address char* address=strDest; assert( (strDest!=NULL)&&(strSrc!=NULL) );//對源地址和目的地址加非0斷言 while(*address)//是while(*strDest!=’\0’)的簡化形式 { //若使用while(*strDest++),則會出錯,因為循環結束後strDest還會執行一次++, //那麼strDest將指向'\0'的下一個位置。/所以要在循環體內++;因為要使*strDest最後指 //向該字符串的結束標誌’\0’。 address++; } while(*address++=*strSrc++) { NULL;//該循環條件內可以用++, }//此處可以加語句*strDest=’\0’;無必要 return strDest;//為了實現鏈式操作,將目的地址返回 } 4 char *mystrcat(char *dst,const char *src) //用自己的方式實現strcat函數功能 5 { 6 char *p=dst; //下面的操作會改變目的指針指向,先定義一個指針記錄dst 7 while(*p!='\0')p++; 8 while(*src != '\0')*p++=*src++; 9 *p='\0'; 10 return dst; 11 }
strcatMATLAB函數
strcat定義
strcat 即 Strings Catenate,橫向連接字符串。
strcat語法
combinedStr= strcat(s1, s2, ..., sN)
strcat描述
將數組 s1,s2,...,sN 水平地連接成單個字符串,並保存於變量 combinedStr中。如果任一參數是元胞數組,那麼結果 combinedStr 是一個元胞數組,否則,combinedStr是一個字符數組。
strcat實例
>> a = 'Hello'
a =
Hello
>> b = ' Matlab'
b =
Matlab
>> c = strcat(a,b)
c =
Hello Matlab
strcat附註
For character array inputs, strcat removes trailing ASCII white-spacecharacters: space, tab, vertical tab, newline, carriage return, and form-feed. To preserve trailing spaces when concatenating character arrays, use horizontal array concatenation, [s1, s2, ..., sN]. See the final example in the following section.
For cell array inputs, strcat does not remove trailing white space.
When combining nonscalar cell arrays and multi-row character arrays, cell arrays must be column vectors with the same number of rows as the character arrays.