最近工作中遇到了string、char *、char []之间的相互转换,今天终于抽出时间将他们之间的转换记录下来,使用的是CodeBlocks软件,编译器为GNU GCC compiler,下面看代码:
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <thread>
#include <stdlib.h>
using namespace std;
int main() {
//string --> char *
string str1 = "hello";
char *p1 = const_cast<char *>(str1.c_str());
printf("p1=%s.\n", p1);
//string --> char c[]
string str2 = "world";
char c[10] = {0};
int len1 = str2.size();
int i = 0;
for (i = 0; i < len1; ++i) {
c[i] = str2[i];
}
c[i] = '\0';
printf("c=%s.\n", c);
//char c[] --> string
char c2[10] = "great";
string str3 = c2;
cout << "str3=" << str3 << endl;
//char * --> string
char *p2 = "wall";
string str4 = p2;
cout << "str4=" << str4 << endl;
//char * -->char []
char *p3 = "china";
char c3[10] = {0};
int len2 = sizeof(c3);
strncpy(c3, p3, len2);
printf("c3=%s.\n", c3);
//char [] -->char *
char c4[10] = "haha";
int len3 = strlen(c4);
char *p4 = new char[len3+1];
strncpy(p4, c4, len3);
printf("p4=%s.\n", p4);
delete []p4;
return 0;
}
运行结果如下: