Overload - (subtraction) so that it removes the first occurrence of the substring on the right from the string on the left and returns the result. : Minus « Overload « C++






Overload - (subtraction) so that it removes the first occurrence of the substring on the right from the string on the left and returns the result.

  
#include <iostream>
#include <string>

using namespace std;

string operator-(const string &left, const string &right);
string operator-=(string &left, const string &right);

int main()
{
  string str("This is a test.");
  string res_str;

  cout << "Contents of str: " << str << "\n\n";

  res_str =  str - "is";
  cout << res_str << "\n\n";

  res_str -= "is";
  cout << res_str << "\n\n";
  cout << str;

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








Related examples in the same category

1.Overload the - relative to MyClass class 1. Overload the - relative to MyClass class 1.
2.Demo: Overload the +, -, and = relative to MyClass.Demo: Overload the +, -, and = relative to MyClass.
3.overload the - operator