请问string中erase是怎么用的

img

img

#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int main()
{
    ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
    int n,cot=0,cot2=0;
    cin>>n;
    string s;
    cin>>s;
    for(int i=0;i<s.size();i++)
    {
        cot2++;
        if(s.find("swust")!=-1) 
        {
        cot++;
        int a = s.find("swust");
        s.erase(a,a+4);
        cout<<s<<endl;
        }
//        s[a] = 1;
//        n=n+4;
    }
    cout<<cot<<" "<<cot2<<endl;
}

img

查看stl标准库的手册,常用在线网站有两个

对应的string::erase帮助文档

有帮助麻烦采纳一下

不知道你这个问题是否已经解决, 如果还没有解决的话:
  • 你可以参考下这个问题的回答, 看看是否对你有帮助, 链接: https://ask.csdn.net/questions/340782
  • 除此之外, 这篇博客: string的常用用法详解中的 (5)erase() 部分也许能够解决你的问题, 你可以仔细阅读以下内容或者直接跳转源博客中阅读:

    erase()两种用法:删除单个元素和删除一个区间内的所有元素。时间复杂度O(N)。

    • 删除单个元素。

    str.erase(it)用于删除单个元素,it为所需要的单个元素的迭代器。

    程序代码:

    #include<iostream>
    #include<string>
    using namespace std;
    int main(){
    	string str = "lichuachua"; 
    	str.erase(str.begin()+1);//删除1号位(从0开始),即 i	  
    	cout<<str<<endl;
    	return 0;
    }

    运行结果:

    • 删除一个区间内的所有元素。

    str.erase(first, last),其中first为需要删除的区间的起始迭代器,而last则为需要删除区间的末尾送代器的下一个地址,也即为删除[first,last)。

    程序代码:

    #include<iostream>
    #include<string>
    using namespace std;
    int main(){
    	string str = "lichuachua"; 
    	//删除[str.begin()+1,str.end()-3] 内的元素,即ichuac 
    	str.erase(str.begin()+1,str.end()-3);	  
    	cout<<str<<endl;
    	return 0;
    }

    运行结果:

    str.erase(pos, length),其中pos为需要开始删除的起始位置, length为删除的字符个数。

    程序代码:

    #include<iostream>
    #include<string>
    using namespace std;
    int main(){
    	string str = "lichuachua"; 
    	str.erase(1,6);	  //从1号位的i开始删除6个
    	cout<<str<<endl;
    	return 0;
    }

    运行结果:


如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^