C++--string类-容量操作

35 篇文章 0 订阅

cplusplus reference–string

cppreference–string

string类对象的容量操作

  • size – 返回字符串的长度
  • length – 返回字符串的长度
  • capacity – 返回当前分配给字符的存储空间的大小,以字节表示
  • max_size – 返回字符串可以达到的最大长度
  • resize – 将字符串调整成n字符的长度
  • reserve – 请求将字符串容量调整为n字符的计划更改
  • clear – 清楚字符串的内容,该字符串变为空字符串,长度为0个字符
  • empty – 返回字符串是否为空
  • shrink_to_fit – 请求字符串以降低其容量以适应其大小。
void test1()
{
	//string类对象支持直接用cin和cout进行输入输出
	string s("hello world");
	cout << s << endl; 
	cout << s.size() << endl;  //11
	cout << s.length() << endl;  //11
	cout << s.capacity() << endl;  //15
	cout << s.max_size() << endl;  //2147483647

	s.clear();//将s中的字符串清空,只是将size清空,不改变底层空间的大小
	cout << s.size() << endl;  //0
	cout << s.capacity() << endl;  //15
	
	//void resize(size_t n, char c);
	s.resize(10, 'a');//将s中的有效字符个数增加到10个,多出来的位置用字符‘a’进行填充
	cout << s << endl;  //aaaaaaaaaa
	cout << s.size() << endl;  //10
	cout << s.capacity() << endl;  //15

	//void resize (size_t n);
	s.resize(15);//将s中的有效字符个数增加到15个,多出的位置用缺省值'\0'进行填充
	cout << s << "over!" << endl;  //aaaaaaaaaa     over!	cout << s.size() << endl;
	cout << s.capacity() << endl;  //15
	s.resize(5);
	cout << s.size() << endl;  //5
	cout << s.capacity() << endl;  //15
}
void test2()
{
	string s;
	//void reserve (size_t n = 0);
	s.reserve(100); //reserve不会改变string中的有效元素个数
	cout << s << endl;  
	cout << s.size() << endl;  //0
	cout << s.capacity() << endl;  //111

	s.reserve(50);
	cout << s << endl;  //reserve参数小于string的底层空间大小时,不会缩小string的底层空间
	cout << s.size() << endl;  //0
	cout << s.capacity() << endl;  //111
}
void test3()
{
	string str = "123";
	cout << str.size() << endl; //3
	cout << str.capacity() << endl; //15
	str.reserve(100);
	cout << str.size() << endl; //3
	cout << str.capacity() << endl; //111
	str.shrink_to_fit(); //降低容量以适应大小
	cout << str.size() << endl; //3
	cout << str.capacity() << endl; //15
}
  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值