目录
1、char[]、char*转string
char[]、插入*转string比较简单,直接赋值即可进行转换
#include<iostream>
#include<string>
using namespace std;
int main()
{
string str;
char x[] = "hello";
char *y = "Hello";
str = x;
cout << "x的值为:" << str << endl;
str = y;
cout << "y的值为:" << str << endl;
return 0;
}
运行结果
2、string转char*、char[]
string转char*有三种方法:
- data();
- c_str();
- copy();
(1)c_str方法
#include<iostream>
#include<string>
using namespace std;
int main()
{
string str;
str="hello world";
const char *y = str.c_str(); //这里一定定义为const char *格式,char * p = (char*)str.data()
cout << "str的值为:" << y << endl;
return 0;
}
运行结果
(2)data方法
#include<iostream>
#include<string>
using namespace std;
int main()
{
string str;
str="hello world";
const char *y = str.data(); //这里一定定义为const char *格式,char * p = (char*)str.data()
cout << "str的值为:" << y << endl;
return 0;
}
运行结果
(3)copy方法
#pragma warning(disable:4996)
#include<iostream>
#include<string>
using namespace std;
int main()
{
string str;
str="world";
char y[20];
str.copy(y, 5, 0);//第二个参数代表复制的个数,第三个代表复制的位置
*(y + 5) = '\0';
cout << "str前5个元素的值值为:" << y << endl;
return 0;
}
运行结果