String容器
1.at()
#include<iostream>
#include<string>
using namespace std;
int main(){
string s="asdfgh";
for(int i=0;i<s.size();i++){
cout<<s.at(i)<<" ";
}
}
2.拼接字符串,"+"或append()
#include<iostream>
#include<string>
using namespace std;
int main(){
string s="asdfgh";
s+="12345";
cout<<s<<endl;
string s2="ghjkl";
s2.append(s);
cout<<s2;
}
3.查找,find(),rfind()
#include<iostream>
#include<string>
using namespace std;
int main(){
string s="abcdefg";
int pos1=s.find("dg");
int pos2=s.find("fg");
cout<<pos1<<endl;
cout<<pos2;
}
#include<iostream>
#include<string>
using namespace std;
int main(){
string s="abbcaabbbbaa";
int pos1=s.find("b");//查找第一次出现的的位置
int pos2=s.rfind("b");//查找第二次出现的位置
cout<<pos1<<"\n"<<pos2;
}
4.replace()替换
#include<iostream>
#include<string>
using namespace std;
int main(){
string s="abbcaabbbbaa";
s.replace(0,4,"11111");
cout<<s;
}
5.compare()字符串的比较
compare()在>时返回1,<时返回-1,==时返回0
大写A比小写a小
#include<iostream>
#include<string>
using namespace std;
int main(){
string a,b;
a="asdf";
b="asdf";
if(a.compare(b)==0){
cout<<"True";
}
else cout<<"False";
}
6.字串函数substr()
#include<iostream>
#include<string>
using namespace std;
int main(){
string a,b;
a="abc12345";
b=a.substr(2,4);
cout<<b;
}
7.插入和删除
insert(int pos,string& str)插入字符串
insert(int pos,int n,char c)在指定位置插入n个字符
erase(int pos,int n)删除从pos开始的n个字符
#include<iostream>
#include<string>
using namespace std;
int main(){
string a;
a="abc12345";
a.insert(2,"###");
cout<<a<<endl;
a.insert(2,10,'*');
cout<<a<<endl;
a.erase(2,5);
cout<<a<<endl;
}