突然發現對字符串函數缺乏系統的了解,所以花了一點時間專門整理下,在此記錄之,以方便自己及有需要的人使用。
C/C++字符串函數的頭文件:string.h
復制函數主要有4個,如下:
1、char * strcpy(char* destination,const char * source);
2、char* strncpy(char* destination,const char* source,size_t num);
3、void * memcpy(void* destination,const void* source,size_t num);
4、void * memmove(void* destination,const void* source,size_t num);
功能及用法說明:
1、strcpy:將由source指針指示的C 字符串(包括結尾字符)復制到destination指針指示的區域中。該函數不允許source和destination的區域有重疊,同時,為了避免溢出,destination區域應該至少和source區域一樣大。
2、strncpy:復制source的前num字符到destination。如果遇到null字符('\0'),且還沒有到num個字符時,就用(num - n)(n是遇到null字符前已經有的非null字符個數)個null字符附加到destination。注意:並不是添加到destination的最后,而是緊跟着由source中復制而來的字符后面。下面舉例說明:
char des[] = "Hello,i am!";
char source[] = "abc\0def";
strncpy(des,source,5);
此時,des區域是這樣的:a,b,c,\0,\0,i,空格,a,m,!
\0,\0並不是添加在!的后面。
這里,需要注意strcpy僅僅復制到null字符就結束了。
3、memcpy:將source區域的前num個字符復制到destination中。該函數不檢查null字符(即將null字符當作普通字符處理),意味着將復制num個字符才結束。該函數不會額外地引入null字符,即如果num個字符中沒有null字符,那么destination中相應字符序列中也沒有null字符。同strcpy的區別:允許將source中null字符后面的字符也復制到destination中,而strcpy和strncpy則不可以。
4、memmove:同memcpy完成同樣的功能,區別是,memmove允許destination和source的區域有重疊。而其他三個函數不允許。
例子:char str[] = "This is a test!";
memmove(str+2,str+10,4);
此時,str變成:Thtests a test!