如何在 C++ 中將 std::string 轉換為 const char* 或 char*?


在本部分中,我們將瞭解如何將 C++ 字串 (std::string) 轉換為 const char* 或 char*。這些格式是 C 樣式的字串。我們有一個稱為 c_str() 的函式。這將幫助我們完成這項任務。它返回指向一個數組的指標,該陣列包含一個空終止的字元序列(即 C 字串),表示字串物件的當前值。

以下是 std::string::c_str 的宣告。

const char* c_str() const;

此函式返回指向一個數組的指標,該陣列包含一個空終止的字元序列(即 C 字串),表示字串物件的當前值。如果丟擲一個異常,則字串中沒有更改。

示例程式碼

 執行演示

#include <iostream>
#include <cstring>
#include <string>

int main () {
   std::string str ("Please divide this sentence into parts");

   char * cstr = new char [str.length()+1];
   std::strcpy (cstr, str.c_str());

   char * p = std::strtok (cstr," ");
   while (p!=0) {
      std::cout << p << '\n';
      p = std::strtok(NULL," ");
   }
   delete[] cstr;
   return 0;
}

輸出

Please
divide
this
sentence
into
parts

更新於:2019 年 7 月 30 日

1K+ 瀏覽量

開啟你的職業生涯

完成課程,獲得認證

立即開始
廣告