標準 C++ 類別的成員函式 c_str()

Rate this post

功能:將string物件轉換成C語言形式的字串常數。

使用格式:const char* c_str ( ) const;

說明:c_str() 演算法會把string物件轉換成C語言形式的字串常數。由於轉換之後的字串已經變成常數,因此無法再任意更改。若有特殊原因必須更改字串常數時,應該先把字串常數儲存到緩衝區(buffer)之後再予以更改。

範例:

// strings and c-strings #include <iostream> #include <cstring> #include <string> using namespace std; int main () { char * cstr, *p; string str ("Please split this phrase into tokens"); cstr = new char [str.size()+1]; strcpy (cstr, str.c_str()); // cstr now contains a c-string copy of str p=strtok (cstr," "); while (p!=NULL) { cout << p << endl; p=strtok(NULL," "); } delete[] cstr; return 0; }

 

ㄚ琪在Windows的命令列下,用g++編譯,輸出:

Please
split
this
phrase
into
tokens

本站部分內容包含聯盟行銷連結。當您透過連結購買商品或服務時,本站將獲得微薄的佣金,這並不會影響您的購買價格,但能支持本站的運作,感謝您的支持。問題詢問

點我分享到Facebook

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *