Conversion of character arrays and strings in C++

When using C++ to solve problems, we often encounter the conversion between character arrays and strings, so we will briefly organize this.

#include<iostream>
#include<string.h>
using namespace std;
int main()
{	

	char str[]={'a','b','c','d','e'}; 
	//一维字符数组转化字符串 
	string tempStr1,tempStr2;
	//法一 
	for(int i=0;i<strlen(str);i++)
	{
		tempStr1+=str[i];	
	}
	//法二
	tempStr2=str;
	cout<<tempStr1<<" "<<tempStr2<<endl; 
	
	//字符串转字符数组
	
	string tempStr3="I LOVE CHINA"; 
	char temp[20];
	int i=0;
	for(i;i<tempStr3.length();i++)
	{
		temp[i]=tempStr3[i];
	}
	temp[i]='\0';
	cout<<temp<<endl;
} 

Guess you like

Origin blog.csdn.net/qq_42027706/article/details/121788583