在 C++ 中,字符串 的 erase 成员函数可以删除 string 对象中的子串,并返回对象自身的引用。
string& erase (size_t pos = 0, size_t n = npos);
参数 | 描述 |
---|---|
pos | 字符串删除的开始位置,默认第一个字符。 |
npos | 要删除的长度,默认删除到最后。 |
返回删除后的字符串的引用。
iterator erase(iterator position);
参数 | 描述 |
---|---|
position | 删除 position 迭代器处的字符。 |
返回删除后的迭代器。
我们使用了 erase 函数,可以删除 position 迭代器处的字符。
iterator erase ( iterator first, iterator last );
参数 | 描述 |
---|---|
first | 要删除的开始迭代器。 |
last | 要删除的结束迭代器。 |
返回删除后的迭代器。
我们使用了 erase 函数,删除从迭代器 first 开始,到迭代器 last 结束的字符串。
C++ erase 函数删除子串
#include <iostream>
using namespace std;
int main()
{
cout << "嗨客网(www.haicoder.net)\n" << endl;
string str1 = "I love HaiCoder and i learn C++ from HaiCoder";
string str2 = "I love HaiCoder and i learn C++ from HaiCoder";
string str3 = "I love HaiCoder and i learn C++ from HaiCoder";
string resStr1 = str1.erase();
string resStr2 = str2.erase(16);
string resStr3 = str3.erase(7, 16);
cout << "resStr1 = " << resStr1 << endl;
cout << "resStr2 = " << resStr2 << endl;
cout << "resStr3 = " << resStr3 << endl;
}
程序运行后,控制台输出如下:
我们首先,定义了三个字符串 变量 str1、str2 和 str3,接着,我们使用了字符串的 erase 函数,没有传入任何参数,从而实现了删除整个字符串。
接着,我们传入了要删除的开始索引,没有传入结束索引,则一直删除到最后,最后,我们传入了要删除的开始索引和长度,从而删除了字符串的片段。
C++ erase 函数删除字符
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "嗨客网(www.haicoder.net)\n" << endl;
string str ("I Love HaiCoder!!!!");
string::iterator it = str.begin() + 16;
str.erase (it);
cout << "Str = " << str << endl;
return 0;
}
程序运行后,控制台输出如下:
我们使用了 erase 函数加上迭代器删除了单个字符。
C++ erase 函数传入迭代器删除字符串
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "嗨客网(www.haicoder.net)\n" << endl;
string str ("I Love HaiCoder!!!!");
string::iterator begin = str.begin() + 16;
string::iterator end = str.end();
str.erase (begin, end);
cout << "Str = " << str << endl;
return 0;
}
程序运行后,控制台输出如下:
我们使用了 erase 函数传入了开始迭代器和结束迭代器删除了字符串。
在 C++ 中,字符串的 erase 成员函数可以删除 string 对象中的子串,并返回对象自身的引用。