Advertisement
cmiN

string replace

Feb 24th, 2012
235
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.59 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4.  
  5.  
  6. void replace(const string& from, const string& to, string& mystr)
  7. {
  8.     int pos = 0;
  9.     while ((pos = mystr.find(from, pos)) != string::npos) {
  10.         mystr.replace(pos, from.size(), to);
  11.         pos += to.size();
  12.     }
  13. }
  14.  
  15.  
  16. int main(int argc, char* argv[])
  17. {
  18.     string from, to, mystr;
  19.     bool fromOn = false, toOn = false, mystrOn = false;
  20.     int last = 0;
  21.     for (int i = 1; i < argc; ++i) {
  22.         string tmp(argv[i]);
  23.         if (!tmp.compare("-f")) {
  24.             fromOn = true;
  25.             last = 1;
  26.         } else if (!tmp.compare("-t")) {
  27.             toOn = true;
  28.             last = 2;
  29.         } else if (!tmp.compare("-s")) {
  30.             mystrOn = true;
  31.             last = 3;
  32.         } else {
  33.             if (last == 1) from.append(tmp + " ");
  34.             else if (last == 2) to.append(tmp + " ");
  35.             else if (last == 3) mystr.append(tmp + " ");
  36.         }
  37.     }
  38.     if (mystrOn) {
  39.         mystr.erase(--mystr.end());
  40.         if (toOn) to.erase(--to.end());
  41.         if (fromOn) {
  42.             from.erase(--from.end());
  43.             replace(from, to, mystr);
  44.         }
  45.         cout << mystr << endl;
  46.     } else {
  47.         cerr << "Usage: " << argv[0] << " [...] -s <string>\n";
  48.         cerr << "Example: " << argv[0] << " -f mere -t portocale -s ana are mere\n\n";
  49.         cerr << "Options:\n";
  50.         cerr << "    -s <string>    input text\n";
  51.         cerr << "    -f <string>    chunk to modify\n";
  52.         cerr << "    -t <string>    with what to replace" << endl;
  53.     }
  54.     return 0;
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement