c++string容器字符串查找替换、比较、提取、插入和删除以及string和c风格的字符串的转换
c++string容器字符串查找替换
#include<string>
#include<iostream>
#include<cstring>
using namespace std;
int main(){
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;
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:
遍历查找完成
www.17171272.***.person.77.com
c++string容器字符串的比较
#include<iostream>
#include<string>
using namespace std;
int main(){
string str1 = "hehe";
string str2 = "haha";
cout<<str1.compare(str1)<<endl;
cout<<str1.compare("lala")<<endl;
cout<<str1.compare("hehe")<<endl;
return 0;
}
c++string容器字符串的提取
#include<iostream>
#include<string>
using namespace std;
int main(){
string str1="hehehe:ha:xixixi:lalala:heihei";
cout<<str1.substr(5,4)<<endl;
int pos = 0;
while(1){
int ret = str1.find(":",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);
cout<<str1<<endl;
str1.erase();
cout<<str1.size()<<endl;
return 0;
}
hellohehe world
hello world
0
string和c风格的字符串的转换
#include<iostream>
#include<string>
using namespace std;
int main(){
string str1;
const char* str2 = "hello str2";
str1 = str2;
cout<<str1<<endl;
string str3="hello str3";
string str4 = const_cast<char*>(str3.c_str());
cout<<str4<<endl;
return 0;
}
hello str2
hello str3