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

相关文章:

  • 2021-05-29
  • 2022-12-23
  • 2021-12-30
  • 2021-06-29
  • 2021-09-11
  • 2022-12-23
  • 2022-12-23
  • 2021-11-21
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-12-02
  • 2022-01-05
  • 2021-12-31
  • 2022-12-23
  • 2021-08-09
相关资源
相似解决方案