Autocorrect Text as a Buffer Changes - C++ STL

C++ examples for STL:map

Description

Autocorrect Text as a Buffer Changes

Demo Code

#include <iostream>
#include <string>
#include <cctype>
#include <map>

using namespace std;

typedef map<string, string> StrStrMap;

class MyTextField {
public:/* ww  w .j a  va2 s.  co m*/
   MyTextField(StrStrMap* const p) : pDict_(p) {}

   void append(char c);
   void getText(string& s) {s = buf_;}

private:
   MyTextField();
   string buf_;
   StrStrMap* const pDict_;
};

void MyTextField::append(char c) {
   if ((isspace(c) || ispunct(c)) &&         // Only do the auto-correct when ws or punct is entered
       buf_.length() > 0 && !isspace(buf_[buf_.length() - 1])) {

      string::size_type i = buf_.find_last_of(" \f\n\r\t\v");

      i = (i == string::npos) ? 0 : ++i;

      string tmp = buf_.substr(i, buf_.length() - i);
      StrStrMap::const_iterator p = pDict_->find(tmp);

      if (p != pDict_->end()) {                   // Found it, so erase and replace
         buf_.erase(i, buf_.length() - i);
         buf_ += p->second;
      }
   }
   buf_ += c;
}

int main() {
   StrStrMap dict;
   MyTextField txt(&dict);

   dict["taht"] = "that";
   dict["right"] = "wrong";
   dict["bug"] = "feature";
   dict["good"] = "bad";

   string tmp = "godd good He's right, taht's a bug.";

   cout << "Original: " << tmp << '\n';

   for (string::iterator p = tmp.begin();
        p != tmp.end(); ++p) {
      txt.append(*p);
   }

   txt.getText(tmp);

   cout << "Corrected version is: " << tmp << '\n';
}

Related Tutorials