轉自:http://zhidao.baidu.com/question/104592558.html
http://blog.csdn.net/xiaoniba10631/article/details/6705214
原型:const char *c_str();
c_str()函數返回一個指向正規C字串的指標, 內容與本string串相同.
這是為了與c語言相容,在c語言中沒有string類型,故必須通過string類對象的成員函數c_str()把string 對象轉換成c中的字串樣式。
注意:一定要使用strcpy()函數 等來操作方法c_str()返回的指標
比如:最好不要這樣:
const char* c;
string s="1234";
c = s.c_str();
因為:這樣做是很危險的:
舉例代碼:
const char* c;
string s="1234";
c = s.c_str();
s.append("abcd");
printf("%s\n", c);
cout << c << endl;
輸出結果為:
1234abcd
1234abcd
分析:指標c會直接指向s,操作同一塊記憶體,而不會新開闢內從空間,這無疑是危險的。
應該這樣用:
char c[20];
string s="1234";
strcpy(c,s.c_str());
再舉個例子
c_str() 以 char* 形式傳回 string 內含字串
如果一個函數要求char*參數,可以使用c_str()方法:
string s = "Hello World!";
printf("%s", s.c_str()); //輸出 "Hello World!"
string.data() : 與c_str()類似,但是返回的數組不以Null 字元終止。
string::copy()舉例:
char c2[11] = {0};
string s2 = "";
s2 = "hello boy!";
int iRtn = s2.copy(c2, 10, 0);//功能為將s2的,從第0個開始的,共10個字元拷貝到c2中,iRtn為拷貝的字元個數,此處為10。
注意:iRtn返回的是實際拷貝的位元組數,當第二個參數比字串本身長時,返回的便是字串長度。