标准库string常用方法
来源:互联网 发布:微课制作软件 编辑:程序博客网 时间:2024/06/06 13:14
- string常用方法
- 定义及初始化
- size 和empty操作
- 操作符
- 关系操作符
- 两个string对象相加
- 支持迭代器
- inserterase操作
- substr操作
- append函数
- replace函数
- find操作
string常用方法
定义及初始化
string类型提供 与vector相同的操作,可视为字符容器,与vetor容器不同的是,string容器不支持以栈方式操作容器,在string类型中不能使用front、back和pop_back操作
string s1; string s2="hello"; cout<<s2<<endl;
size() 和empty操作
string s1; string s2="hello"; cout<<s2.size()<<endl; if(s1.empty()){ cout<<""<<endl; }
[]操作符
string s2="hello"; for (int i=0; i<s2.size(); i++) { cout<<s2[i]<<" "<<endl; }
关系操作符
如果两个string对象的字符不同,则比较第一个不匹配的字符
如果两个string对象的长度不同,且短的string对象与长的string对象的前面部分相同,则短的string对象小于长的string对象
string s1 = "hello world"; string s2 = "hello"; string s3 = "hiya"; string s4="hello world"; if(s1 >s2){ cout <<"s1小于s2"<<endl; } if(s1<s3) { cout<<"s1小于s3"<<endl; } if(s1 == s4) { cout<<"s1等于s4"<<endl; }
两个string对象相加
string对象可以通过加法被定义为链接,使用+或+=连接起来
string s1 = "hello world "; string s2 = "hello"; string s3 =s1 + s2; cout<<s3<<endl;
支持迭代器
string s1 = "hello world "; string s2 = "hello"; string s3 =s1 + s2; string::iterator iter=s3.begin(); while(iter != s3.end()) { cout<<*iter++<<endl; }
insert、erase操作
string s3 = "hello world "; string::iterator iter=s3.begin(); s3.insert(s3.begin(),3,'c'); while(iter!=s3.end()){ cout<<*iter++<<endl; } s3.erase(s3.begin(),s3.begin()+5); iter=s3.begin(); while(iter!=s3.end()){ cout<<*iter++<<endl; }
只适用于string类型的操作
substr操作
string s3 = "hello world "; cout<<s3.substr(1,3)<<endl;
append函数
用于修改string对象
string s3 = "hello world "; s3.append("facebook"); cout<<s3<<endl;
replace函数
I.s.replace(pos,len,args). 删除s中从下标pos开始开始的len个字符
string s3 = "hello world "; cout<<s3.replace(0,2,"ccc")<<endl;
II. s.replace(b,e,args),删除迭代器b和e范围内所有的字符,用args替换
string s3 = "hello world "; s3.replace(s3.begin(),s3.begin()+3,"facebook"); cout<<s3<<endl;
find操作
string s3 = "hello world "; string::size_type pos1=s3.find("llo"); cout<<pos1<<endl;
0 0
- 标准库string常用方法
- java标准库中ByteBuffer转String的方法
- 【标准库】string 库
- 标准库String类型
- 标准库string
- 标准库string类型
- 标准库string类型
- 标准库string类型
- 标准库类型 string
- c++标准库------string
- 标准库string类型
- C++标准库string
- 标准库类型string
- C++标准库string
- 标准库类型string
- 标准库 string 类型
- 标准库string类型
- 标准库类型string
- Spring学习(1)
- UIImagePickerController从拍照、图库、相册获取图片
- 黑马程序员------数组排序总结(Day12)
- glFinish()和glFlush()函数详解
- 2015070107 - 工作反思
- 标准库string常用方法
- iOS-生成国际化包-配置App多语言支持
- 七月一号课堂心得
- PHP开发环境搭建
- 关于IO的今天学到的一点东西
- C语言中数组作为函数参数的问题
- 黑马程序员-OC语言-@property关键字介绍及使用(听课笔记)
- Spring Security处理器
- Exception in thread "main" java.io.IOException: Permission denied