C++:string.erase函数

2023-04-26 09:17:32

erase函数

erase函数的原型:

string& erase ( size_t pos = 0, size_t n = npos );
iterator erase ( iterator position );
iterator erase ( iterator first, iterator last );

也就是说,erase函数有三种用法:

  • erase(pos, n):删除从pos开始的n个字符
  • erase(position):删除position处的一个字符,其中position是一个string类型的迭代器
  • erase(first, last):删除从first到last之间的字符,其中first和last都是string类型的迭代器(包括first,不包括last)

(注意:s.end()指的是最后一个字符的再后一个位置)

例子

#include<iostream>
#include<string>
using namespace std;
int main()
{
    string s("cat dog apple");
    string::iterator it;
    // (1)
    s.erase(4,3);
    cout<<s<<endl;
    // (2)
    it = s.begin()+3;
    s.erase(it);
    cout<<s<<endl;
    // (3)
    s.erase(s.begin()+3, s.end()-1);
    cout<<s<<endl;
}

运行结果:

D:\develop\Cpp-practice (master -> origin)
λ g++ test.cpp -o test.exe

D:\develop\Cpp-practice (master -> origin)
λ .\test.exe
cat  apple
cat apple
cate

参考链接

  • 作者:Yvettre
  • 原文链接:https://blog.csdn.net/Yvettre/article/details/79826136
    更新时间:2023-04-26 09:17:32