string::erase

erase

std::basic_string::erase

basic_string& erase( size_type index = 0, size_type count = npos );
(1) 
 (2) 
iterator erase( iterator position );
(C++11 前)
iterator erase( const_iterator position );
(C++11 起)
 (3) 
iterator erase( iterator first, iterator last );
(C++11 前)
iterator erase( const_iterator first, const_iterator last );
(C++11 起)
   

从 string 移除指定的字符。

1) 移除始于  index 的  min( countsize()  - index ) 个字符。
2) 移除位于  position 的字符。
3) 移除范围  [first, last) 中的字符。

参数

index-要移除的首个字符
count-要移除的字符数
position-指向要移除的字符的迭代器
first, last-要移除的字符范围

返回值

1)  *this
2) 指向立即后随被擦除字符的迭代器,或若不存在这种字符则为  end()
3) 指向擦除前  last 所指向字符的迭代器,或若不存在这种字符则为  end()

异常

1) 若  index > size() 则为  std::out_of_range 。
2-3) (无)

任何情况下,若因任何原因抛出异常,则此函数无效果(强异常保证)。 (C++11 起)

示例

#include <iostream>
#include <algorithm>
#include <string>
 
int main()
{
    std::string s = "This is an example";
    std::cout << s << '\n';
 
    s.erase(0, 5); // 擦除 "This "
    std::cout << s << '\n';
 
    s.erase(std::find(s.begin(), s.end(), ' ')); // 擦除 ' '
    std::cout << s << '\n';
 
    s.erase(s.find(' ')); // 从 ' ' 到字符串尾裁剪
    std::cout << s << '\n';
}

输出:

This is an example
is an example
isan example
isan

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值