string中erase方法

2023-04-08 13:36:31

注意,只有两种方法:

①位置:起始位置,个数

②迭代器:删除位置的迭代器或者起始位置的

1.

中间放起始位置

或者起始位置和个数

#include<iostream>
#include<string>
using namespace std;

int main(){
    string str = "hello c++! +++";
    // 从位置pos=10处开始删除,直到结尾
    // 即: " +++"
    str.erase(10);
    cout << '-' << str << '-' << endl;
    // 从位置pos=6处开始,删除4个字符
    // 即: "c++!"
    str.erase(6, 4);
    cout << '-' << str << '-' << endl;
    return 0;
}

2.

迭代器[ )

#include<iostream>
#include<string>
using namespace std;

int main(){
    string str = "hello c++! +++";
    // 删除"+++"前的一个空格
    str.erase(str.begin()+10);
    cout << '-' << str << '-' << endl;
    // 删除"+++"
    str.erase(str.begin() + 10, str.end());
    cout << '-' << str << '-' << endl;
    return 0;
}

3.迭代器位置的单个字符

iterator erase(const_iterator position)

删除迭代器位置处的单个字符, 并返回下个元素的迭代器

4.pop_back():删除最后一个元素

5.常与find函数一起用

string longer("That's a funny hat.");
//size_type loc1 = longer.find("hat"); // 存在
size_type loc1 = longer.find("hello"); //不存在
if (loc1 == string::npos)
    cout<< "not found" <<endl;
  • 作者:Bak_
  • 原文链接:https://blog.csdn.net/weixin_53225765/article/details/122944589
    更新时间:2023-04-08 13:36:31