【C++】string字符串查找替换、比较、提取、插入和删除
•
算法结构
【C++】string字符串查找替换、比较、提取、插入和删除
- 字符串的查找替换
- 字符串的比较
- 字符串的提取
- 字符串的插入和删除
- Reference
字符串的查找替换
//c++string容器字符串查找替换
#include
#include
#include
using namespace std;
int main(){
//int find(const string &str,int pos=0)const;
//查找第一次出现的位置,从pos开始查找
string str1 = "ehhe:haha:xixi:haha:heihei";
string tmp = "haha";
cout<<str1.find(tmp)<<endl;
cout<<str1.find(tmp,10)<<endl;
cout<<str1.find("haha")<<endl;
//string& replace(int pos,int n,const string& str);
//替换str第一次出现的位置,从pos开始查找
str1.replace(5,4,"###");
cout<<str1<<endl;
string str2="www.17171272.sex.person.77.com";
while(1){
int ret = str2.find("sex");
if(ret>str2.size()){
cout<<"遍历查找完成"<<endl;
break;
}
str2.replace(ret,strlen("sex"),"***");
}
cout<<str2<<endl;
return 0;
}
5 15 5 ehhe:###:xixi:haha:heihei 遍历查找完成 www.17171272.***.person.77.com
字符串的比较
//c++string容器字符串的比较
#include
#include
using namespace std;
int main(){
//compare函数在>时返回1, <是返回-1,等于时返回0
string str1 = "hehe";
string str2 = "haha";
cout<<str1.compare(str1)<<endl;//1
cout<<str1.compare("lala")<<endl;//-1
cout<<str1.compare("hehe")<<endl;//0
return 0;
}
字符串的提取
//c++string容器字符串的提取
#include
#include
using namespace std;
int main(){
//string substr(int pos=0,int n=n)const;
//返回由pos开始的n个字符组成的字符串
string str1="hehehe:ha:xixixi:lalala:heihei";
cout<<str1.substr(5,4)<<endl;
int pos = 0;
while(1){
int ret = str1.find(":",pos);//从pos开始寻找":"
if(ret<0){
break;
}
string tmp =str1.substr(pos,ret-pos);
cout<<tmp<<endl;
pos=ret+1;
}
return 0;
}
e:ha hehehe ha xixixi lalala
字符串的插入和删除
//c++string容器字符串的插入和删除
#include
#include
using namespace std;
int main(){
string str1="hello world";
str1.insert(5,"hehe");
cout<<str1<<endl;
str1.erase(5,4);//删除hehe
cout<<str1<<endl;
//清空字符串
str1.erase();
cout<<str1.size()<<endl;
return 0;
}
hellohehe world hello world 0
Reference
Link
加油!
感谢!
努力!
本文来自网络,不代表协通编程立场,如若转载,请注明出处:https://www.net2asp.com/b2c1d5e431.html
