char*,const char*和string的相互轉換
阿新 • • 發佈:2019-01-25
1. string轉const char*
string s = "abc";
const char* c_s = s.c_str();
2. const char*轉string
直接賦值即可
const char* c_s = "abc";
std::string a=c_s;
3. string轉char*
string s = "abc";
char* c;
const int len = s.length();
c = new char[len+1];
strcpy(c,s.c_str());
4. char*轉string
char* c = "abc";
string s(c);
5. const char*轉char*
const char* cpc = "abc";
char* pc = new char[100];//足夠長
strcpy(pc,cpc);
6. char*轉const char*
直接賦值即可
char* pc = "abc";
const char* cpc = pc;