string、char[]、char*、const char* 相互转换
string、char[]、char*、const char* 相互转换
https://blog.csdn.net/ksws0292756/article/details/79432329【 4 - 14 】
(1).string => const char* 较直接
const char* constc = nullptr; //初始化const char*类型,并赋值为空
constc= str.c_str(); //string类型转const char*类型
(2).char*、const char* => string 直接
const char* constc = "Hello World!"; //初始化const char* 类型,并具体赋值
std::string str; //初始化string类型
str= constc; //const char*类型转string类型
(3).string => char* 不直接
char* c = nullptr; //初始化char*类型,并赋值为空
const char* constc = nullptr; //初始化const char*类型,并赋值为空
constc= str.c_str(); //string类型转const char*类型
c= const_cast<char*>(constc); //const char*类型转char*类型
(4).string => char[] 循环赋值
std::string str = "HelloWorld!";
char arrc[20] = {0};
for (int i = 0; i < str.length(); i++) //string类型转char[]类型
{
arrc[i]=str[i];
}
(5).char* 、const char* => string 直接
const char* constc = "Hello World!";
std::string str;
str= constc; //const char*类型转string类型
(6).const char* => char* 函数转化
const char* constc = "Hello World!";
char* c = nullptr;
c= const_cast<char*>(constc);
(7).const char* => char[]; 函数转化
const char* constc = "Hello World!";
char arrc[20] = { 0 };
strncpy_s(arrc,constc,20);
(8).char* => const char*; 直接
constc= c;
(9). char* => char[]; 函数转化,同const char*
char* c = "HelloWorld!";
char arrc[20] = { 0 };
strncpy_s(arrc,c,20); //char*类型转char[] 类型
(10).char[] => char*\const char*\string
str= arrc;
constc= arrc;
c= arrc;
string、char[]、char*、const char*; 输出都一样
printf只能输出c语言中的内置数据,string不是c语言内置数据;
cout可以输出string字符串,是因为string中重载了“<<”操作符;
printf_s("%s\n", arrc);
printf_s("%s\n", str.c_str());
printf_s("%s\n", constc);
printf_s("%s\n", c);