【快速入门 C++ STL】 demo 演示一:string

/*********************/
/*    demo string    */
/*********************/
#define _SCL_SECURE_NO_WARNINGS 
#include<string>
#include<iostream>
#include<algorithm>

using namespace std;

//构造仿函数:把1变为0,非0变为1
struct MyStruct
{
	char operator()(char& obj)
	{
		if (obj == '0') return '1';
		else return '0';
	}
};

int main()
{
	char buf[128];
	string str = "abcdefabcdefabc";

	//copy
	str.append("def");
	str = str + "abc";
	cout << "str:\t" << str << endl;

	//find
	int offset = 0;
	offset = str.find("abc", offset);
	cout << endl;
	cout << "offset:\t" << offset << endl;

	//count
	int count = 0;
	while (offset != string::npos)
	{
		count++;
		offset += 3;
		offset = str.find("abc", offset);
	}
	cout << endl;
	cout << "count:\t" << count << endl;

	//replace
	offset = 0;
	str.replace(offset, 2, "000");
	cout << endl << "replace" << endl;
	cout << "str1:\t" << str << endl;

	//copy to buf copy(buf, n, offset);
	offset = 1;
	str.copy(buf, 3, offset);
	cout << "buf:\t" << buf[0] << buf[1] << buf[2] << endl;

	//erase
	string::iterator it = str.begin();
	it = find(it, str.end(), 'a');
	while (it != str.end())
	{
		it=str.erase(it);//删除迭代器会把it也删除,但erase函数会返回下一个迭代器位置
		it = find(it, str.end(), 'a');
	}
	cout << endl << "erase" << endl;
	cout << "str:\t" << str << endl;

	//transform   transform(first, end, out, toupper);
	MyStruct myfun;
	transform(str.begin(), str.end(), str.begin(), myfun);
	cout << endl << "transform" << endl;
	cout << "str:\t" << str << endl;

	system("pause");
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值