C++ string初始化、string赋值操作、string拼接操作

以下介绍了string的六种定义方式,还有很多,这个只是简单举例

#include<iostream>

using namespace std;

int main() {
	
	//1 无参构造
	string s1;
	cout << s1 << endl;

	//2 初始化构造
	string s2 ({'h', 'h', 'l', 'l', 'o'});
	cout << s2 << endl;

	//3 字符串初始化
	string s3("xiaoxiao");
	cout << s3 << endl;
	
	//4 字符串的前n个字符
	string s4("xiaoxiaoxiao", 6);
	cout << s4 << endl;
	
	//5 拷贝构造
	string s5(s4);
	cout << s5 << endl;
	

	// a 个 b
	string s6(8, 'o');
	cout << s6 << endl;




    return 0;

}

以下是string的六种赋值操作,以下是代码

#include<iostream>
using namespace std;

int main() {
	//1 字符串常量的赋值
	string s1;
	s1 = "xiaoxiao";
	cout << s1 << endl;

	//2 字符串变量的赋值
	string s2;
	s2 = s1;
	cout << s2 << endl;

	//3 字符常量赋值
	string s3;
	s3 = 'a';
	cout << s3 << endl;

	//4 assign 接口1
	string s4;
	s4.assign("xiaoxiao");
	cout << s4 << endl;

	//5 assign 接口2
	string s5;
	s5.assign("xiaoxiaoxiao", 8);
	cout << s5 << endl;

	//6 assign 接口3
	string s6;
	s6.assign(s5);
	cout << s6 << endl;

	//7 a个b
	string s7;
	s7.assign(8, '6');
	cout << s7 << endl;



}

string拼接操作,代码见下

#include<iostream>

using namespace std;

int main() {
	// 1 + 运算符重载
	string s1 = "dada";
	string s2 = "xiao";

	s1 = s1 + s2;
	cout << s1 << endl;
	
	// 2 += 运算符重载
	string s3 = "dada";
	string s4 = "xiao";

	s4 += "daxiao";
	cout << s4 << endl;

	// 3 append
	string s5 = "abc";
	s5.append("def");
	s5.append("hijklmn", 4); // 取这个的前四个,进行对应字符串的拼接,这个4代表个数
	s5.append("opqrst", 2, 3);// 取从第二个开始,取三个进行拼接
    cout << s5 << endl;
	// 4 push_back
	string s6 = "abb";
	s6.push_back('6');
	cout << s6 << endl;




	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值