1 //char數組和string的轉換 2 #include<iostream> 3 #include<string.h> 4 using namespace std; 5 int main() 6 { 7 char ch[]="hello world"; 8 // string s=ch;/* string可以直接用char數組賦值*/ 9 string s(ch);/* 對string賦值char數組差不多就這兩種*/ 10 cout<<"ch="<<ch<<endl; 11 printf("ch=%s\n",ch); 12 cout<<"s="<<s<<endl;/*printf("s=%s",s); string不能直接用printf輸出,需要用.c_str()*/ 13 printf("s=%s\n",s.c_str()); 14 string a="helloworldaaa"; 15 const char *c; 16 c=a.c_str(); 17 cout<<"c="<<c<<endl; 18 c=s.c_str(); 19 cout<<"c="<<c<<endl;/* 對const char* 數組賦值,可以用string.c_str()*/ 20 const char *c1; 21 c1=a.data();/* .data 和.c_str()類似,只是字符串末尾沒有了\0*/ 22 cout<<"c1="<<c1<<endl; 23 char c2[100];/* 用strcpy的話,就不能是指針類型,必須給定char數組長度*/ 24 strcpy(c2,a.c_str()); 25 cout<<"c2="<<c2<<endl; 26 }
一切盡在注釋中。