字串函式---strcpy()與strncpy()詳解及實現
阿新 • • 發佈:2019-02-08
一、strcpy()與strncpy()
strcpy():strcpy(dest,src); strcpy把src所指向以'\0'結尾的字串複製到dest所指的陣列中,返回指向dest的指標。
當sizeof(dest)>=sizeof(src)時,拷貝正確,並在dest字串後面加入'\0';
當sizeof(dest)<sizeof(src)時,拷貝出錯。
strncpy():strncpy(dest,src,n); strncpy把src所指向以'\0'結尾的字串的前n個字元複製到dest所指的陣列中,返回指向dest的指標。
當n>=sizeof
當n<sizeof(src)時,只拷貝src前n-1個字串到dest,不會為dest字串後面加入'\0';
示例程式碼:
#include<iostream> #include<string> using namespace std; int main() { char a[]="lanzhihui is a good boy!"; //以下strcpy char b[30]; char c[30]; char d[30]; strcpy(b,a); //strcpy進行簡單的拷貝,除了拷貝a陣列的字串外,還會將a陣列後面的'\0'拷貝給陣列b. cout<<"b:"<<b<<endl;//當陣列b的儲存空間 sizeof(b)>=sizeof(a) 時,正確拷貝,並在陣列b字串後加'\0'。 //當陣列b的儲存空間 sizeof(b)<sizeof(a) 時,拷貝出錯。 cout<<"strlen(c):"<<strlen(strcpy(d,strcpy(c,a)))<<endl;//先是將a拷貝給c,strcpy返回c的地址,將c拷貝給d,並返回d的地址,再求字串d的字元長度。 //這是拷貝strcpy()函式拷貝完後,返回目標字串地址的原因,可以支援鏈式表達等。 cout<<"c:"<<c<<endl; cout<<"d:"<<d<<endl; //以下strncpy char e[10]; char f[30]; char g[30]; strncpy(f,a,sizeof(f)); //sizeof(f)>=sizeof(a) 時,正確拷貝, strncpy(g,a,10); //拷貝a中前9個字元到g中,必須手動為g陣列加入'\0' g[9]='\0'; //n<sizeof(a)時,必須有這一句,不然輸出出錯 strncpy(e,a,sizeof(e)); e[sizeof(e)-1]='\0'; //sizeof(e)<sizeof(a)時,必須有這一句,不然輸出出錯 cout<<"e:"<<e<<endl; cout<<"f:"<<f<<endl; cout<<"g:"<<g<<endl; system("pause"); return 0; }
舉例理解strcpy()與strncpy()函式拷貝以 '\0' 結束:
#include<iostream> #include<string> using namespace std; int main() { char s[]="lanzhihui\0 is a good boy!"; char name[30]; strcpy(name,s);//拷貝以'\0'結束 cout<<name<<endl;//輸出以'\0'結束 strncpy(name,s,sizeof(name));//拷貝以'\0'結束 cout<<name<<endl;//輸出以'\0'結束 system("pause"); return 0; }
二、strcpy()與strncpy()實現
根據對strcpy()與strncpy()函式功能的測試,寫出實現的程式碼:
#include<iostream>
#include<string>
#include<assert.h>
using namespace std;
char *strcpy_m(char *dest,const char *str)
{
assert((dest!=NULL)&&(str!=NULL));
char *cp=dest;
while((*cp++=*str++)!='\0')
{
//
}
return dest;
}
char *strncpy_m(char *dest,const char *str,int n)
{
assert((dest!=NULL)&&(str!=NULL));
char *cp=dest;
while(n&&(*cp++=*str++)!='\0')
{
n--;
}
if(n)
{
while(--n)
*cp++='\0';
}
return dest;
}
int main()
{
char a[]="lanzhihui is a good boy!";
//以下strcpy_m
char b[30];
char c[30];
char d[30];
strcpy_m(b,a);
cout<<"b:"<<b<<endl;
cout<<"strlen(c):"<<strlen(strcpy_m(d,strcpy_m(c,a)))<<endl;
cout<<"c:"<<c<<endl;
cout<<"d:"<<d<<endl;
//以下strncpy_m
char e[10];
char f[30];
char g[30];
strncpy_m(f,a,sizeof(f));
strncpy_m(g,a,10);
g[9]='\0';
strncpy_m(e,a,sizeof(e));
e[sizeof(e)-1]='\0';
cout<<"e:"<<e<<endl;
cout<<"f:"<<f<<endl;
cout<<"g:"<<g<<endl;
system("pause");
return 0;
}
可見自己寫的strcpy_m()函式與strncpy_m()函式與庫函式執行結果一樣。