上次在家看了下《程序员宝典》自己写了段代码实现了下其中的一个面试题 //此段代码是为了设计出《程序员面试宝典》第十四章14.5节面试题二而来。 #include<iostream> //#include<vector> //#include<cctype> #include<string> #include<algorithm> using namespace std; int main() { //vector<string> coll; //string s("askdaskaskdaskg"); //string s1("ask"); string s,s1; cout<<"请输入主字符串S:"<<endl; getline(cin,s);////////////运用getline函数可以处理来自stream的字符串从而可以从键盘输入 cout<<"请输入子字符串S1:"<<endl; getline(cin,s1); string::size_type pos;//索引 pos=s.find(s1);//将查找返回的位置赋值给索引 //string::size_type num; int num; num=s1.size(); cout<<"子字符串字符数为:"; cout<<num<<endl; while(pos!=string::npos)//如果不存在就会返回nops标志, { s.erase(pos,num);//注意此处第一参数为要删除的字符的索引,第二参数为要删除的字符的数量即num cout<<"删除后其字符串为:"<<s<<endl; pos=pos+num+1; if(pos!=string::npos)//此处为进行继续往下搜索 { pos=s.find(s1); } } cout<<"最终的字符串为:"<<s<<endl; }