std::string 有两个方法:data() 和 c_str(),都是返回该字符串的const char类型,那如何转换成非const的char呢?
下面展示三种方法:
char* char_test = (char*)test.c_str();
char* charPointer = &test[0];
char* charCast = const_cast<char*>(test.c_str());
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "Hello World" << endl;
std::string test = "hello string";
printf("%s", test.c_str());
char* char_test = (char*)test.c_str();
printf("\nchar_test: %s", char_test);
char* charPointer = &test[0];
printf("\ncharPointer: %s", charPointer);
char* charCast = const_cast<char*>(test.c_str());
printf("\ncharCast: %s", charCast);
return 0;
}
顺便提一句:C++11以后,string 的 data() 方法和 c_str() 方法作用一样,没区别了。that is, c_str() and data() perform the same function. (since C++11)