1. 程式人生 > >C++中string erase 函式的使用

C++中string erase 函式的使用

C++中string erase函式的使用

2017年04月05日 21:02:17 閱讀數:4286
erase函式的原型如下:
(1)string& erase ( size_t pos = 0, size_t n = npos );(2)iterator erase ( iterator position );(3)iterator erase ( iterator first, iterator last );也就是說有三種用法:(1)erase(pos,n); 刪除從pos開始的n個字元,比如erase(0,1)就是刪除第一個字元(2)erase(position);刪除position處的一個字元(position是個string型別的迭代器)(3)erase(first,last);刪除從first到last之間的字元(first和last都是迭代器)下面給你一個例子:
複製程式碼#include <iostream>
#include <string>usingnamespace 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.”return0; }