string 、char*、const char *
string 、char*、const char *
1.string to char* 方式1 std::string str = "string"; char* chr = const_cast<char*>(str.c_str()) 方式2 string str = "some string" ; char *cstr = &str[0]; 方式3 std::string str = "string"; const char *cstr = str.c_str(); Note that it returns a const char *; you aren’t allowed to change the C-style string returned by c_str(). If you want to process it you’ll have to copy it first: std::string str = "string"; char *cstr = new char[str.length() + 1]; strcpy(cstr, str.c_str()); // do stuff delete [] cstr; Or in modern C++: std::vector<char> cstr(str.c_str(), str.c_str() + str.size() + 1); // use &chars[0] as a char* 2. char* to string 方式1:直接赋值: char c[] = "this is a char array"; const char* t = "const char"; string s = t; string ss = c; 同理const char*转string: const char* cc = "this is a const exp"; string s(cc, cc + strlen(cc)); 3. char* 和const char* const char* src = "this is a const exp"; char* ch = const_cast<char*>(src); const char* dst = static_cast<const char*>(ch); cout << ch << endl; cout << dst << endl;