1.string转const char*
string str = "abc";
const char *pa = str.data();//data()函数不会添加'\0'结束符
cout << pa << endl;
const char *p = str.c_str();//c_str()会在数据的末尾添加'\0'结束符,多数用于使用字符串场合。
cout << p << endl;
但是,上面这种用法很不安全,因为p最后指向的内容是垃圾值,str对象被析构了。而且c_str()返回的是一个临时指针,不能对其进行操作。
2.string转char*
string s = "abcd";
char *ch;
ch = (char*)malloc((s.length()) * sizeof(char));
s.copy(ch, s.length(),0);//把当前串中以0开始的s.length()个字符拷贝到以ch为起始位置的字符数组中,返回实际拷贝的数目
cout << ch;
3.string转char[]
1)strcpy_s
#include <iostream>
using namespace std;
#include <string>
int main()
{
char ch[5];
string s = "abcd";
strcpy_s(ch, s.c_str());
cout << ch << endl;
return 0;
}
2)遍历添加
#include <iostream>
using namespace std;
#include <string>
int main()
{
string pp = "helloworld";
char p[20];
int i;
for (i = 0; i < pp.length(); i++)
{
p[i] = pp[i];
}
p[i] = '\0'; //添加结束符
cout << p << endl;
return 0;
}
4.const char *或者const char []或者char []转string
#include <iostream>
using namespace std;
#include <string>
int main()
{
string a;
const char* b = "study";
const char c[] = "study well";
char p[20] = "helloworld";
a = b;
cout << a << endl;
cout << a.length() << endl;
a = c;
cout << a << endl;
cout << a.length() << endl;
a = p;
cout << a << endl;
cout << a.length() << endl;
return 0;
}
5.char[]转char*或者const char[]转const char*
#include <iostream>
using namespace std;
#include <string>
int main()
{
char a[20] = "hello world";
char* p = a;
cout << p << endl;
const char a1[20] = "hello world";
const char* p1 = a1;
cout << p1 << endl;
return 0;
}
6.const char*转char[]
1)strcpy_s
#include <iostream>
using namespace std;
#include <string>
int main()
{
char arr[20];
const char* tmp = "helloworld";
strcpy_s(arr, tmp);
cout << arr << endl;
return 0;
}
2)循环遍历
#include <iostream>
using namespace std;
#include <string>
int main()
{
char arr[20];
const char* tmp = "hello world";
int i = 0;
while (*tmp != '\0')
{
arr[i++] = *tmp++;
}
arr[i] = '\0'; //添加结束符
cout << arr << endl;
return 0;
}
7.char*转string
#include <iostream>
using namespace std;
#include <string>
int main()
{
char a[10] = "hello";
char *b = a;
string c = b;
cout << a << endl;
cout << b << endl;
cout << c << endl;
return 0;
}