C++——string(2)

本文详细介绍了C++中string类的非成员函数如rfind、substr、find、find_first_not_of等的使用方法,以及assign、insert、erase和swap等操作在处理字符串时的应用实例。
摘要由CSDN通过智能技术生成
5. string类非成员函数

上面的几个接口大家了解一下,下面的OJ题目中会有一些体现他们的使用。string类中还有一些其他的 操作,这里不一一列举,大家在需要用到时不明白了查文档即可。

试用rfind、substr、find、find_first_(not)_of

void test_string9()
{
	//string s1("file.cpp");
	string s1("file.c.tar.zip");

	// 拿到文件的后缀
	size_t pos1 = s1.rfind('.');
	if (pos1 != string::npos)
	{
		string suffix = s1.substr(pos1);
		//string suffix = s1.substr(pos1, s1.size()-pos1);

		cout << suffix << endl;
	}
	else
	{
		cout << "没有后缀" << endl;
	}

	string url2("https://legacy.cplusplus.com/reference/string/string/substr/");
	string url1("http://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&rsv_idx=1&tn=65081411_1_oem_dg&wd=%E5%90%8E%E7%BC%80%20%E8%8B%B1%E6%96%87&fenlei=256&rsv_pq=0xc17a6c03003ede72&rsv_t=7f6eqaxivkivsW9Zwc41K2mIRleeNXjmiMjOgoAC0UgwLzPyVm%2FtSOeppDv%2F&rqlang=en&rsv_dl=ib&rsv_enter=1&rsv_sug3=4&rsv_sug1=3&rsv_sug7=100&rsv_sug2=0&rsv_btype=i&inputT=1588&rsv_sug4=6786");

	string protocol, domain, uri;
	size_t i1 = url1.find(':');
	if (i1 != string::npos)
	{
		protocol = url1.substr(0, i1 - 0);
		cout << protocol << endl;
	}

	// strchar
	size_t i2 = url1.find('/', i1 + 3);
	if (i2 != string::npos)
	{
		domain = url1.substr(i1 + 3, i2 - (i1 + 3));
		cout << domain << endl;

		uri = url1.substr(i2 + 1);
		cout << uri << endl;
	}

	// strstr
	size_t i3 = url1.find("baidu");
	cout << i3 << endl;

	std::string str("Please, replace the vowels in this sentence by asterisks.");
	cout << str << endl;

	// strtok
	std::size_t found = str.find_first_not_of("aeiou");
	while (found != std::string::npos)
	{
		str[found] = '*';
		found = str.find_first_not_of("aeiou", found + 1);
	}
	cout << str << endl;

	cout << (url1 < url2) << endl;

	string ss1 = "xxx";
	string ss2 = "yyy";

	string ret = ss1 + ss2;
	cout << ret << endl;

	string ret1 = ss1 + "yyyy";
	string ret2 = "yyyy" + ss2;
}

试用assign、insert、erase、swap

void test_string10()
{
	string s1("xhello world");
	cout << s1 << endl;

	s1.assign(" xxxxx");
	cout << s1 << endl;

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

	s1.erase(5, 3);
	cout << s1 << endl;

	s1.erase();
	cout << s1 << endl;

	string s2("hello world hello bit");
	/*s2.replace(5, 1, "20%");
	cout << s2 << endl;*/

	/*size_t pos = s2.find(' ');
	while (pos != string::npos)
	{
		s2.replace(pos, 1, "20%");
		pos = s2.find(' ');
	}
	cout << s2 << endl;*/

	// insert/erase/replace
	// 能少用就要少用,因为基本都要挪动数据,效率不高
	string s3;
	s3.reserve(s2.size());
	for (auto ch : s2)
	{
		if (ch != ' ')
		{
			s3 += ch;
		}
		else
		{
			s3 += "20%";
		}
	}
	cout << s3 << endl;
	s2.swap(s3);
	cout << s2 << endl;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值