std::basic_string<CharT,Traits,Allocator>::erase
来自cppreference.com
                    
                                        
                    < cpp | string | basic string
                    
                                                            
                    | (1) | ||
|   basic_string& erase( size_type index = 0, size_type count = npos );  | 
(C++20 前) | |
|   constexpr basic_string& erase( size_type index = 0, size_type count = npos );  | 
(C++20 起) | |
| (2) | ||
|   iterator erase( iterator position );  | 
(C++11 前) | |
|   iterator erase( const_iterator position );  | 
 (C++11 起)  (C++20 前)  | 
|
|   constexpr iterator erase( const_iterator position );  | 
(C++20 起) | |
| (3) | ||
|   iterator erase( iterator first, iterator last );  | 
(C++11 前) | |
|   iterator erase( const_iterator first, const_iterator last );  | 
 (C++11 起)  (C++20 前)  | 
|
|   constexpr iterator erase( const_iterator first, const_iterator last );  | 
(C++20 起) | |
从 string 移除指定的字符。
2) 移除位于 
position 的字符。3) 移除范围 
[first, last) 中的字符。参数
| index | - | 要移除的首个字符 | 
| count | - | 要移除的字符数 | 
| position | - | 指向要移除的字符的迭代器 | 
| first, last | - | 要移除的字符范围 | 
返回值
1) *this
2) 指向立即后随被擦除字符的迭代器,或若不存在这种字符则为 
end()3) 指向擦除前 
last 所指向字符的迭代器,或若不存在这种字符则为 end()异常
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
参阅
|   清除内容  (公开成员函数)  |