C++:string类中的常见接口

默认构造函数

在string类中有许多的默认构造函数,本文选择其中的三类最常见的构造方式来讲解

string()//空字符串
string(const char* str)//用字符串去创建
string(const string& s)//拷贝构造函数
string(size_t n,char c)//创建一个n个字节的字符为c的字符串

下面是实现 

	string s1;
	string s2("hello world");
	string s3(s2);
	string s4(10, 'a');

访问方式及关于容量的操作的方法

先来介绍下标访问法和+=的操作法

	string s1("hello");
	string s2("liutao");
	s1 += ' ';//+=既可以尾插字符串也可以尾插字符
	s1 += s2;
	cout << s1 << endl;
	//写
	for (size_t i = 0; i < s1.size(); i++)
	{
		s1[i] += 1;
	}
	//读
	for (size_t i = 0; i < s1.size(); i++)
	{
		cout << s1[i] << ' ';
	}
	cout << endl;

这里就和数组的访问方法一样(最推荐)

迭代器访问法

string s1("hello");
string s2("liutao");
s1 += ' ';//+=既可以尾插字符串也可以尾插字符
s1 += s2;
cout << s1 << endl;
//string::iterator it = s1.begin();
auto it = s1.begin();//简便写法
//写
while (it != s1.end())
{
	*it -= 1;
	it++;
}
//读
it = s1.begin();
while (it != s1.end())
{
	cout << *it << " ";
	it++;
}
cout << endl;
//范围for
for(auto ch : s1)
{
    cout<<ch<<endl;
}

逆置访问

	string s1("hello world");
	string::const_reverse_iterator it = s1.rbegin();
	while (it != s1.rend())
	{
		cout << *it << endl;
		it++;
	}

与正序访问相差不大

capacity、size、empty、reserve和resize

	string s1("hello world");
	string s2("hello");
	cout << s1.size() << endl;//返回s1的字符串长度
	cout << s2.size() << endl;
	cout << s1.capacity() << endl;//返回s1的容量
	s1 += "aaaaaaaaa";
	cout << s1.capacity() << endl;
	s1.clear();
	cout << s1.capacity() << endl;
	cout << s1.empty() << endl;//返回s1是否为空
	string s1;
	size_t sz = s1.capacity();
	//s1.reserve(100);
	s1.resize(100,'x');
	for (int i = 0; i < 100; i++)
	{
		s1.push_back('a');
		if (sz != s1.capacity())
		{
			sz = s1.capacity();
			cout << "capacity change: " << sz << endl;
		}
	}

这个可以看到每次增加容量的以后大小 其中reserve可以预开设定的空间,resize也可以预开一定大小的空间,但是resize会将开了的空间全部占用,默认为\0

insert

	string s1;
	string s2("2");
	s1 += '1';
	s1 += "345";
	s1.insert(s1.begin(), '0');
	s1.insert(2, s2);
	cout << s1 << endl;
	s1.erase(2, 10);
	cout << s1 << endl;

insert函数实现了很多重载函数,但是大同小异,第一个参数放要插入的位置,第二个参数写要插入的字符

find+npos+substr+rfind+getline

	string s1("test.cpp.zip");
	string s2("test.c");
	string s3("test.txt");
	size_t pos1 = s1.rfind('.');//从后面开始找 
	if (pos1 != string::npos)
	{
		cout << s1.substr(pos1) << endl;
	}
	size_t pos2 = s2.find('.');
	if (pos2 != string::npos)
	{
		cout << s2.substr(pos2) << endl;
	}
	size_t pos3 = s3.find('.');
	if (pos3 != string::npos)
	{
		cout << s3.substr(pos3) << endl;
	}

int main()
{
	string s1;
	//cin<<s1;//有空格时不能用
	getline(cin, s1);
	size_t pos = s1.rfind(' ');//用后面开始查找
	cout << s1.size() - (pos + 1) << endl;
	return 0;
}

这几个函数一般是搭配使用的可以用于查找字符串,分离字符串。但是npos的就是代表四十二万多的位置,也就意味着字符串结尾

  • 21
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值