string用法总结

目录

1. 构建操作 

2.赋值操作 

 3.取值操作

4.拼接操作

5.查找操作 

6.替换操作 

7.比较操作 

8.子串操作 

9.插入删除操作 


1. 构建操作 

void Test1()
{
	cout << endl << "构造操作: " << endl;
	string s1; //默认构造
	string s2(10, 'a'); //有参
	string s3("asdfgh"); //传字符串初始化
	string s4(s3); //拷贝构造

	cout << s1 << endl;
	cout << s2 << endl;
	cout << s3 << endl;
	cout << s4 << endl;
	cout << endl;
}

2.赋值操作 

void Test2()
{
	cout << endl << "赋值操作: " << endl;
	string s1; //默认构造
	string s2("s2"); //传字符串初始化
	
	s1 = "s2"; //字符串
	cout << s1 << endl;

	s1 = s2; //string类
	cout << s1 << endl;
	
	s1 = 'a'; //字符
	cout << s1 << endl;

	s1.assign("s2"); //成员
	cout << s1 << endl;
}

 3.取值操作

void Test3()
{
	cout << endl << "取值操作: " << endl;
	string s1("asdfgh");

	//访问越界,直接崩溃
	for (int i = 0; i < s1.size(); i++) {
		cout << s1[i] << " ";
	}
	cout << endl;

	//访问越界,抛出异常out_of_range
	for (int i = 0; i < s1.size(); i++) {
		cout << s1.at(i) << " ";
	}
	cout << endl;

	try {
		cout << s1.at(100) << endl; //抛出异常
	}
	catch (...) {
		cout << "访问越界" << endl;
	}
}

4.拼接操作

void Test4()
{
	cout << endl << "拼接操作: " << endl;
	string s1("asdfgh");

	s1 += "test1";
	cout << s1 << endl;

	string s2 = "test2";
	s1 += s2;
	cout << s1 << endl;

	string s3 = "test3";
	s1.append(s3);
	cout << s1 << endl;
}

5.查找操作 

void Test5()
{
	cout << endl << "查找操作: " << endl;
	string s1("asdfghdf");
	int pos = s1.find("df"); //第一次出现的位置
	cout << pos << endl;

	pos = s1.rfind("df"); //最后一次出现的位置
	cout << pos << endl;
}

6.替换操作 

void Test6()
{
	cout << endl << "替换操作: " << endl;
	string s1("asdfghdf");
	s1.replace(0, 3, "111"); //从序号0开始的3个字符
	cout << s1 << endl;
}

7.比较操作 

void Test7()
{
	cout << endl << "比较操作: " << endl;
	string s1("asdfghdf");
	string s2("asdfghdf");

	if (!s1.compare(s2)) {
		cout << "相同" << endl;
	} else {
		cout << "不相同" << endl;
	}
}

8.子串操作 

void Test8()
{
	//string substr(int pos = 0, int n = count) const 返回pos开始的n个字符组成的字符子串
	cout << endl << "子串操作: " << endl;
	string s1("asdfghdf");

	cout << "从2开始的3个字符组成的子串: " << s1.substr(2, 3) << endl;
}

9.插入删除操作 

void Test9()
{
	//void insert(int pos, string str)
	//void erase(int pos, string str)
	cout << endl << "插入删除操作: " << endl;
	string s1("asdfghdf");

	s1.erase(0, 4);
	cout << s1 << endl;

	s1.insert(0, "asdf");
	cout << s1 << endl;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值