目录
今天做题遇到了char数组和string间的相互转换的问题,网上搜有点散,来整理一下。
char数组转string
采用直接赋值的方法,如下:
#include<iostream>
using namespace std;
int main(){
char c[]="hello world!";
string str=c;//将c[0]的地址赋给str
cout<<str;
}
string转char指针和char数组
一.转char指针
使用string中的data()函数
头文件:#include <string.h>
函数原型为:
const char* data() const noexcept
代码示例:
#include<iostream>
using namespace std;
int main(){
string str="hello world!";
const char *c=str.data();
cout<<c;
}
注意:定义c时最好将类型设为const char*,如果设为char*有可能会出问题
二.转char数组
使用strcpy()函数
头文件:#include <string.h> 和 #include <stdio.h>
函数原型为:
char *strcpy(char* dest, const char *src);
代码示例:
#include<iostream>
using namespace std;
int main(){
string str="hello world!";
char c[str.length()];//c数组大小自定,需大于等于str的长度
strcpy(c,str.data());
puts(c);//打印c数组并换行
}
如有疑问欢迎私信或评论区留言!