string 與 char* 互轉
阿新 • • 發佈:2019-02-03
一、string轉換為char*有3中方法:
1.data
string str="good boy";
const char *p=str.data();
2.c_str
string str="good boy";
const char *p=str.c_str();
- copy
string str="good boy";
char p[20];
str.copy(p,5,0); //這裡5,代表複製幾個字元,0代表複製的位置
*(p+5)='\0'; //要手動加上結束符
或者:
string str="good boy";
char *p;
int len = str .length();
p=(char *)malloc((len+1)*sizeof(char));
str.copy(p,len,0);
二、char*轉換為string
char* s="good boy";
string str=s;
或者
char s[20]="good boy";
string str=s;
三、string轉換成char[]
string str = "good boy";
char p[20];
for(int i=0;i<str.length();i++)
p[i] = str[i];
p[str.length()] = '\0';
或者
string str="good boy";
char p[20];
str.copy(p,5,0);
*(p+5)='\0';