char*,const char*和string 互转

 

1. string转const char*

1 string s = "abc";
2 const char* c_s = s.c_str();

 

 

2. const char*转string

1 //直接赋值即可
2 const char* c_s = "abc";
3 string s(c_s);

 

 

3. string转char*

1 string s = "abc";
2 char* c;
3 const int len = s.length();
4 c = new char[len+1];
5 strcpy(c,s.c_str());

 

 

4. char*转string

1 char* c = "abc";
2 string s(c);

 

 

5. const char*转char*

1 const char* cpc = "abc";
2 char* pc = new char[100];//足够长
3 strcpy(pc,cpc);

 

 

6. char*转const char*

1 //直接赋值即可
2 char* pc = "abc";
3 const char* cpc = pc;

 

posted @ 2015-12-18 17:21  Ace's  阅读(298)  评论(0编辑  收藏  举报