c++ string的詳細用法(7)data()與c_str()與copy()的區別

string a="123456";

1.c_str(),data()可以生成一個const char* 的指針,可以指向一個空字符終止的地址。

const char* str=nullptr;
str=a.c_str(); //結果爲 str="123456";
str=a.data(); //結果爲 str="123456";

但是如果改變string a的值,str的值隨之改變
a="abcedf";
cout<<str<<endl; //結果爲 str="abcdef";

2.如果不想讓其指針指向的值改變可以使用copy()函數(如果不知道copy()函數如何使用,請看我的上一篇copy()的使用方法)
char* str = new char[64];
str[a.copy(str, a.size(), 0)]='\0';
cout << str << endl; //結果爲 str="123456";

//改變string a的值
a="abcd";
cout<< str <<endl; //結果爲 str="123456";

發佈了20 篇原創文章 · 獲贊 118 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章