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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM