C++ examples for STL:string
Implement operator-( ) and operator-=( ) for objects of type string:
#include <iostream> #include <string> using namespace std; string operator-(const string &left, const string &right); string operator-=(string &left, const string &right); int main()/* w ww . ja va 2s. co m*/ { string str("This is a test."); string res_str; cout << "Contents of str: " << str << "\n\n"; // Subtract "is" from str and put the result in res_str. res_str = str - "is"; cout << "Result of str - \"is\": " << res_str << "\n\n"; res_str -= "is"; cout << "Result of res_str -= \"is\": " << res_str << "\n\n"; cout << "Here is str again: " << str << "\nNotice that str is unchanged by the preceding " << "operations." << "\n\n"; cout << "Here are some more examples:\n\n"; // Attempt to subtract "xyz". This causes no change. res_str = str - "xyz"; cout << "Result of str - \"xyz\": " << res_str << "\n\n"; // Remove the last three characters from str. res_str = str - "st."; cout << "Result of str - \"st.\": " << res_str << "\n\n"; // Remove a null string, which results in no change. res_str = str - ""; cout << "Result of str - \"\": " << res_str << "\n\n"; return 0; } string operator-(const string &left, const string &right) { string::size_type i; string result(left); i = result.find(right); if(i != string::npos) result.erase(i, right.size()); return result; } string operator-=(string &left, const string &right) { string::size_type i; i = left.find(right); if(i != string::npos) left.erase(i, right.size()); return left; }