您的位置:首页 > 其它

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

2012-12-30 15:22 851 查看
本文详细介绍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;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: