字符串的查找替换
//c++string容器字符串查找替换
#include<string>
#include<iostream>
#include<cstring>
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<iostream>
#include<string>
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<iostream>
#include<string>
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<iostream>
#include<string>
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.toymoban.com/news/detail-662326.html
努力!文章来源地址https://www.toymoban.com/news/detail-662326.html
到了这里,关于【C++】string字符串查找替换、比较、提取、插入和删除的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!