如何在 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
广告