erase

C++中的erase方法

erase函数的原型如下:

1string& erase ( size_t pos = 0, size_t n = npos );

2iterator erase ( iterator position );

3iterator erase ( iterator first, iterator last );

也就是说有三种用法:

1erase(pos,n); 删除从pos开始的n个字符,比如erase(0,1)就是删除第一个字符

2erase(position);删除position处的一个字符(position是个string类型的迭代器)

3erase(first,last);删除从firstlast之间的字符(firstlast都是迭代器)

#include <string>  
using namespace std;  
  
int main ()  
{  
  string str ("This is an example phrase.");  
  string::iterator it;  
  
  // 第(1)种用法  
  str.erase (10,8);  
  cout << str << endl;        // "This is an phrase."  
  
  // 第(2)种用法  
  it=str.begin()+9;  
  str.erase (it);  
  cout << str << endl;        // "This is a phrase."  
  
  // 第(3)种用法  
  str.erase (str.begin()+5, str.end()-7);  
  cout << str << endl;        // "This phrase."  
  return 0;  
}  

猜你喜欢

转载自blog.csdn.net/qq_40893490/article/details/79248628