如何將 std::string 轉換為 C++ 中的 const char* 或 char*?
您可以使用 string 類的 c_str() 方法獲取包含字串內容的 const char*。
示例
#include<iostream>
using namespace std;
int main() {
string x("hello");
const char* ccx = x.c_str();
cout << ccx;
}輸出
這將產生以下輸出 -
hello
要獲取 char*,請使用 copy 函式。
示例
#include<iostream>
using namespace std;
int main() {
string x("hello");
// Allocate memory
char* ccx = new char[s.length() + 1];
// Copy contents
std::copy(s.begin(), s.end(), ccx)
cout << ccx;
}輸出
這將產生以下輸出 -
hello
廣告
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP