The C++ erase() function program example
Compiler: Visual C++ Express Edition 2005
Compiled on Platform: Windows XP Pro SP2
Header file: Standard
Additional library: none/default
Additional project setting: Set project to be compiled as C++
Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)
Other info: none
To do: Using the C++ erase() member function to remove an element or a range of elements in a string from a specified position.
To show: How to use the C++ erase() member function to remove an element or a range of elements in a string from a specified position.
// the C++ erase() program example
#include <string>
#include <iostream>
using namespace std;
int main(void)
{
// using a range
string str1("Testing the erase() part I");
basic_string <char>::iterator Str1Iter;
cout<<"str1 string object is: "<< str1<<endl;
// don't forget the null character
Str1Iter = str1.erase(str1.begin() + 4, str1.end() - 6);
cout<<"Operation: str1.erase(str1.begin()+4, str1.end()-6)"<<endl;
cout<<"The first element after those removed is: "<<*Str1Iter<<endl;
cout<<"The modified str1 string object is: "<<str1<<endl;
// erasing a char pointed to by an iterator
string str2("Testing the erase() part II");
basic_string <char>::iterator Str2Iter;
cout<<"\nstr2 string object is: "<<str2<<endl;
Str2Iter = str2.erase(str2.begin() + 3);
cout<<"Operation: str2.erase(str2.begin() + 3)"<<endl;
cout<<"The first element after those removed is: "<<*Str2Iter<<endl;
cout<<"The modified str2 string object is: "<<str2<<endl;
// erasing a number of chars after a char
string str3("Testing the erase() part III"), NewStr3;
cout<<"\nThe original str3 string object is: "<<str3<<endl;
NewStr3 = str3.erase(6, 8);
cout<<"Operation: str3.erase(6, 6)"<<endl;
cout<<"The modified NewStr3 string object is: "<<NewStr3<<endl;
return 0;
}
Output example:
str1 string object is: Testing the erase() part I
Operation: str1.erase(str1.begin()+4, str1.end()-6)
The first element after those removed is: p
The modified str1 string object is: Testpart I
str2 string object is: Testing the erase() part II
Operation: str2.erase(str2.begin() + 3)
The first element after those removed is: i
The modified str2 string object is: Tesing the erase() part II
The original str3 string object is: Testing the erase() part III
Operation: str3.erase(6, 6)
The modified NewStr3 string object is: Testinase() part III
Press any key to continue . . .