C++ string和char类型字符串转换代码

#include<iostream>
#include<string>
#include<cstring>
using namespace std;
int main(int argc, char const *argv[])
{
	//char转string
	//直接赋值
	string s;
	const char *a = "1234";
	// char *a = "1234";
	char b[] = "56789";
	s = a;
	cout<<"s = "<<s<<endl;
	printf("s = %s\n", s.c_str());
	s = b;
	cout<<"s = "<<s<<endl<<endl;


	//string转char
	string s2 = "abcdefg";
	const char *c1 = s2.c_str();
	cout<<"c1 = "<<c1<<endl;
	const char *c2 = s2.data();
	cout<<"c2 = "<<c2<<endl<<endl;

	char *c3 = (char *)malloc((20)*sizeof(char));;
	s2.copy(c3, 4, 0);//表示从s2字符串 截取0-4的字符出来拷贝到c3中
	cout<<"len "<<strlen(c3)<<endl;
	cout<<"c3 = "<<c3<<endl;
	printf("c3 = %s\n\n", c3);

	char c4[20];
	string s3="1234";
	strcpy(c4,s3.c_str());//安全形式
	cout<<"c4 = "<<c4<<endl;

	return 0;
}

C++  string和char类型字符串转换代码

上一篇:docker 安装mysql


下一篇:二叉树+负载均衡+MySQL+Redis+高并发-拼多多Java开发1234面 终于上岸了