string.c_str()用法與注意事項 及string::copy()與string.data()

來源:互聯網
上載者:User

轉自: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返回的是實際拷貝的位元組數,當第二個參數比字串本身長時,返回的便是字串長度。

 

 

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.