C++STL学习笔记02

string容器

1、string容器基本概念

string类本不是STL的容器,但是它与STL容器有着很多相似的操作,因此,把string放在这里一起进行介绍。string与c风格的字符串相比有以下特点:

  • char*是一个指针,而string是一个类,string封装了char*指针来管理这个字符串,是一个char*型的容器
  • string封装了很多实用的方法,如查找find(),拷贝copy(),删除delete(),替换replace(),插入insert()
  • string在使用过程中不用考虑内存的管理,不用担心越界与内存释放问题

2、string类常用操作示例

#include<iostream>
#include<string>
#include<vector>
#include<stdexcept>

using namespace std;

void test01() {

	//构造
	string str1;//无参构造
	string str2("Tom");//有参构造初始化
	string str3(str2);//拷贝构造
	string str4(2, 'm');

	//赋值
	str1 = "Bob";//用char*给string赋值
	str3 = str2;//用string给string赋值
	string str5;
	str5.assign("acesf",3); //截取char*的前三个字符对其进行赋值
	string str6;
	str6.assign("abcdefgh",3,3);//从第3开始截取三个字符赋值

	//存取
	cout<<str6[2]<<endl;//中括号越界直接异常退出
	cout << str6.at(2) << endl;//at越界会抛出一个out_of_range异常
	try
	{
		//str6[10];
		str6.at(10);
	}
	catch (out_of_range &e) 
	{
		cout << e.what() << endl;
	}

	//拼接 string& operator+/append()
	string s1 = "我爱";
	string s2 = "北京";
	//s1 += s2;
	s1.append(s2);
	cout << s1 << endl;

	//查找
	string s3 = "skfdjhgsdjh";
	int pos1=s3.find("djh");//有的话返回第一个字符的小标,如果没有的话返回-1
	int pos2 = s3.rfind("djh");//优先从右边开始找
	cout << pos1 << endl << pos2 << endl;

	//替换
	s3.replace(1,3,"aaaa");//把下标1-3的字符串替换成aaaa
	cout << s3 << endl;;

	//比较
	string s4 = "abcd";
	string s5 = "sbcde";
	if (s4.compare(s5) == 0) {
		cout << "s4 == s5 "<< endl;
	}
	else if (s4.compare(s5)>0) {
		cout << "s4>s5" << endl;
	}
	else{
		cout << "s4<s5" << endl;
	}

	//截取
	string s6 = "abcdef";
	string sub = s6.substr(2,3);//从下标2开始截取3个字符
	cout << sub << endl;
	string address = "www.baidu.com.cn";
	vector<string>v1;
	int start=0;
	int pos3 = 0;
	while (pos3 != -1) {
		pos3 = address.find(".",start);
		v1.push_back(address.substr(start, pos3-start));
		start = pos3 + 1;
	}
	for (vector<string>::iterator it = v1.begin(); it < v1.end(); it++) {
		cout <<*it<< endl;
	}

	//插入删除
	s6.insert(1, "111");
	s6.erase(1, 3);

}

int main() {
	test01();
	return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值