string 、char* 、 char []的转换

1、string->char*

(1)data

string s = "goodbye";
const char* p=str.data();

(2)c_str()

string s = "goodbye";
const char* p=str.c_str();

(3)copy

string str="hmmm";
char p[50];
str.copy(p, 5, 0);//这里5代表复制几个字符,0代表复制的位置,
*(p+5)=‘\0’;//注意手动加结束符!!!

2、char* -> string

可以直接赋值。

string s;
char *p = "hello";//直接赋值
s = p;

3、string->char[]

先得出长度,在再逐个字符赋值

string s1="hello";
char s2[6];
int i=0;
for(;i<s1.length();i++) s2[i]=s1[i];
s2[i] = '\0';

4、char->string

直接赋值

猜你喜欢

转载自www.cnblogs.com/pacino12134/p/11264504.html