C++ char*,const char*,string的相互转换(转)
1. string转const char*
1
2
|
string s = "abc" ; const char * c_s = s.c_str(); |
2. const char*转string
直接赋值即可
1
2
|
const char * c_s = "abc" ; string s(c_s); |
3. string转char*
1
2
3
4
5
|
string s = "abc" ; char * c; const int len = s.length(); c = new char [len+1]; strcpy (c,s.c_str()); |
4. char*转string
1
2
|
char * c = "abc" ; string s(c); |
5. const char*转char*
1
2
3
|
const char * cpc = "abc" ; char * pc = new char [100]; //足够长 strcpy (pc,cpc); |