文章目录
前言
string和char*,作为C++中常用的数据类型,经常需要进行相互转换,故此总结转换方法。
一、std::string 转 char*
1.使用string的data方法
string str = "hello world!";
const char *p1 = str.data();
cout << p1 << endl;
2.使用string的c_str方法``
string str = "hello world!";
char *p2 = const_cast<char*>(str.c_str());
cout << p2 << endl;
3. 使用string的copy方法
string str="hello world";
char *p4;
int len = str.length();
p4 = (char *)malloc((len + 1) * sizeof(char));
str.copy(p4, len, 0);
*(p4 + len) = '\0';
4.使用vector方法
string str="hello world";
vector<char> chars(str.begin(), str.end());
chars.push_back('\0');
char *p6 = &chars[0];
5.使用string的连续存储功能
string str="hello world";
char* p7 = &*str.begin();
std::cout << p7<<endl;
二、char* 转std::string
const char* s = "test";
string str1 = s;
cout<<str1<< endl;
char s1[20] = "test char trans";
string str2 = s1;
cout << str2 << endl;
三、示例程序
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
//string转char*5
string str = "hello world!";
//1.data
const char *p1 = str.data();
cout << p1 << endl;
//2.c_str
char *p2 = const_cast<char*>(str.c_str());
cout << p2 << endl;
//3.copy
char p3[20];
str.copy(p3, 5, 0); //这里5,代表复制几个字符,0代表复制的位置
*(p3+5) = '\0'; //要手动加上结束符
cout << p3 << endl;
char *p4;
int len = str.length();
p4 = (char *)malloc((len + 1) * sizeof(char));
str.copy(p4, len, 0);
*(p4 + len) = '\0';
cout << p4 << endl;
char *p5 = new char[str.length() + 1];
strcpy_s(p5,str.length() + 1, str.c_str());
cout << p5<<endl;
vector<char> chars(str.begin(), str.end());
chars.push_back('\0');
char *p6 = &chars[0];
cout << p6<<endl;
char* p7 = &*str.begin();
std::cout << p7<<endl;
const char* s = "test";
string str1 = s;
cout<<str1<< endl;
char s1[20] = "test char trans";
string str2 = s1;
cout << str2 << endl;
system("pause");
}