赋值给字符数组

方法一

按字符的逐个赋值给数组,如下所示

#include<iostream> 
#include<string.h>
using namespace std;

int main(){
	char s2[5]={'h','e','l','l','o'};
	
	for(int i=0;i<5;i++)
		cout<<s2[i];
		
	return 0;
}

运行结果

方法二

#include<iostream>
using namespace std;

int main(){
	char n[20]={"hello world"};
	cout<<n<<endl;
	
	return 0;
}

运行结果

方法三

#include<iostream>
#include<cstring>
using namespace std;

int main(){
	char n[20];
	string s="hello,world!";
	strcpy(n,s.c_str());
	
	cout<<n<<endl;
	
	return 0;
}

运行结果

 

赋值给字符数组指针

 将字符串作为一个整体直接赋值给数组。如下所示。

#include<iostream> 
#include<string.h>
using namespace std;

int main(){
	char s[] = {"hello"};
	
	for(int i=0;i<5;i++)
		cout<<s[i];
		
	return 0;
}

运行结果

 

注意:

    1.这种情况下,字符数组不能声明长度。

    2.这种字符数组的整体赋值只能在字符数组初始化时使用,不能用于字符数组的赋值。

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐