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;
}