C C 字串函式之複製函式

2021-06-27 07:07:25 字數 1368 閱讀 5545

**:

突然發現對字串函式缺乏系統的了解,所以花了一點時間專門整理下,在此記錄之,以方便自己及有需要的人使用。

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!

C C 字串函式之複製函式

突然發現對字串函式缺乏系統的了解,所以花了一點時間專門整理下,在此記錄之,以方便自己及有需要的人使用。c c 字串函式的標頭檔案 string.h 複製函式主要有4個,如下 1 char strcpy char destination,const char source 2 char strncpy...

C C 字串函式之複製函式

c c 字串函式的標頭檔案 string.h 複製函式主要有4個,如下 1 strcpy 將由source指標指示的c 字串 包括結尾字元 複製到destination指標指示的區域中。該函式不允許source和destination的區域有重疊,同時,為了避免溢位,destination區域應該至...

字串之複製函式

字串之複製函式 strcpy函式 函式原型 char strcpy char dest,const char src memcpy函式 原型 extern void memcpy void dest,void src,unsigned int count 用法 include 功能 由src所指記憶...