string基本的类成员函数的使用(at、length、size、begin、empty、resize)

本文详细介绍string类的较简单也比较基本的成员函数的使用样式:

 at/length/clear/begin/empty/resize

1  at  返回字符串中某个位置的处的字符,类似数组的操作

2  length、size计算字符串的长度

3 clear 删除全部字符

4  begin 返回string类变量中第一个元素的迭代器

5  empty 判断字符串是否为空

6 resize 重新分配空间,将多分配出的空间用给出的字符参数填充

 

下面通过一个程序来展示上面的函数应用及格式:

// the functions of string
#include<iostream>
#include<string>
using namespace std;
int main()
{
	string str("Bill Gates");
	//the usage of length/size
	int len1=str.length();
	int len2=str.size();
	cout<<"len1="<<len2<<"  "<<"len2="<<len2<<endl;
    //str.begin()
    cout<<"str.begin()="<<*str.begin()<<endl;
	//the usage of str.at()
	cout<<"the usage of .at():"<<endl;
	for(int i=0;i<len1;i++)
	{
		if(i%2)
			cout<<str.at(i)<<" ";
	}
	cout<<endl;
    //the usage of resize()
	cout<<"the usage of .resize()"<<endl;
	str.resize(len1+2,'B');
	cout<<str<<endl;
    
	cout<<"use the .empty() judge  the string"<<endl;
    if(!str.empty())
		cout<<"I am not empty!"<<endl;

	return 0;
}


 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值