C++中string的erase()函数

C++中string erase函数的使用
erase函数的原型如下:
(1)string& erase ( size_t pos = 0, size_t n = npos );
(2)iterator erase ( iterator position );
(3)iterator erase ( iterator first, iterator last );

注意:erase函数的返回值是一个指向被删除元素的下一个元素的迭代器。 

一、erase(pos, n),删除从下标pos开始的n个字符。

#include <bits/stdc++.h>
using namespace std;

int main()
{
    string str("All that exists is what's ahead.");
    string a, b;
    a = str.erase(9,7);
    //删除从下标为9的位置开始的7个字符
    cout << a << endl; //输出 All that is what's ahead.
    return 0;
}

二、erase( it ),删除it位置的字符,注意it是迭代器类型。

#include <bits/stdc++.h>
using namespace std;

int main()
{
    string str("All that exists is what's ahead.");
    auto it = str.begin() + 4; // auto自动类型推断
    str.erase(it);
    cout << str << endl; //输出 All hat exists is what's ahead.
    return 0;
}

三、erase(first, last),删除[first, last]区间内的字符,注意first和last是迭代器类型。

#include <bits/stdc++.h>
using namespace std;

int main()
{
    string str("All that exists is what's ahead.");
    auto first = str.begin() + 4;
    auto last = str.begin() + 9;
    str.erase(first, last);
    cout << str << endl; //输出 All exists is what's ahead.
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值