怎样对string对象初始化?

1、默认初始化

string s; //s是一个空串

2、使用字符串字面值初始化

string s1=“hello world”; //拷贝初始化
string s2(“hello world”); //直接初始化
注意:s1、s2的内容不包括’\0’

3、使用其他字符串初始化

string s2=s1; //拷贝初始化,s1是string类对象
string s2(s1); //直接初始化,s1是string类对象

4、使用单个字符初始化

string s(3 ‘a’); //直接初始化,s的内容是aaa
#include<iostream>
#include<string>
using namespace std;

int main(){
	string s1;
	string s2="hello world!";
	string s3("hello world!");
	string s4=s2;
	string s5(s2);
	string s6(3,'a');
	
	cout<<"s1: "<<s1<<endl;
	cout<<"s2: "<<s2<<endl;
	cout<<"s3: "<<s3<<endl;
	cout<<"s4: "<<s4<<endl;
	cout<<"s5: "<<s5<<endl;
	cout<<"s6: "<<s6<<endl;
	
	return 0;
}
运行后为:
s1:
s2: hello world!
s3: hello world!
s4: hello world!
s5: hello world!
s6: aaa

上一篇:八进制数转十进制

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值