在这篇文中对之前不熟悉的string函数进行简单梳理,熟悉的就一笔带过。
1.返回string的长度
string s="hello world!";
int n = s.size();
//n=12;

2.使用迭代器进行顺序访问
string s= "hello world!";
for(string::iterator it = str.begin(); it!=str.end();,it++){cout>>*it}
这里仅贴出代码,迭代器的使用先挖个坑,之后再细学。

3.对元素操作
(1)insert()
string s= "hello world!";
str.insert(str.size()," end world");
//str = "hello world! end world"
insert(a,str)
在原字符串的长度a处插入字符串str,原字符串顺延
(2)erase()
str.erase(0,13);
//str="end world"
str.erase(3);
//str="end"
erase()有如上所述的两种用法
有2个参数a,b时表示从第a个字符开始删除b个字符
有1个参数a时表示从第a个字符开始删除剩余所有字符
(3) clear()
str.clear();
//str=""
clear()函数表示清空某字符串

4.find()函数
string str="hello world!";
int found=str.find("world");
if(found!=string::npos) cout<<"fint it at "<<found<<endl;
find()函数找到则返回某字符或字符串首次出现的位置,若找不到则返回string::npos

5.substr()函数
string str1="hello world!";
string s1=str1.substr(0,5);//s1="hello"
string s2=str2.substr(6); //s2="world!"
可见,用法类似于erase函数