convert between char* and std::string

char* to std::string

  std::string has a constructor for this: 

const char *s = "Hello, world!";
std::string str(s);

  note: Make sure thar your char* isn't NULL, or else the behavior is undefined.

  if you already know size of the char*, use this instead

char* data = ...;
int size = ...;
std::string myString(data,size);

  note: This doesn't use strlen.

  if string variable already exists, use assign():

std::string myString;
char* data = ...;
int size = ...;
myString.assign(data,size);

 

 std::string to char*

  your can use the funtion string.c_str():

std::string my_string("testing!");
const char* data = my_string.c_str();

  note: c_str() returns const char*, so you can't(shouldn't) modify the data in a std::string via c_str(). If you intend to change the data, then the c string from c_str() should be memcpy'd.

std::string my_string("testing!");
char *cstr = new char[my_string.length() + 1];
strcpy(cstr,my_string.c_str());
//do stuff
delete[] cstr;

Reference

  (1) http://stackoverflow.com/questions/1195675/convert-a-char-to-stdstring

  (2) http://stackoverflow.com/questions/7352099/stdstring-to-char

原文地址:https://www.cnblogs.com/danshui/p/2564603.html