//=============================================================================

#include <iostream>
#include <map>
#include <string>
using namespace std;

//-----------------------------------------------------------------------------

void replace_placeholder(string& s, const map<string, string>& dict)
{
   for (
      string::size_type pos1 = s.find('$');
      pos1 != string::npos;
      pos1 = s.find('$', pos1))
   {
      string::size_type pos2 = s.find('$', pos1 + 1);

      // Key hat kein abschliessendes '$'
      if (pos2 == string::npos)
      {
         string key = s.substr(pos1 + 1);
         string val = "$Key \"" + key + "\" hat kein Ende";
         s.replace(pos1, key.length() + 1, val);
         return;
      }

      // Maskiertes '$' - daher '$$' => '$'
      if (pos2 == pos1 + 1)
      {
         s.erase(pos1++, 1);
         continue;
      }

      // Es gibt einen Key - ist er auch im Dictonary?
      string key = s.substr(pos1 + 1, pos2 - pos1 - 1);
      map<string, string>::const_iterator fit = dict.find(key);
      if (fit == end(dict))
      {
         string val = "$Key \"" + key + "\" ist unbekannt$";
         s.replace(pos1, pos2 - pos1 + 1, val);
         pos1 += val.length();
      }
      else
      {
         const string& val = fit->second;
         s.replace(pos1, pos2 - pos1 + 1, val);
         pos1 += val.length();
      }
   }
}

int main()
{
   cout << "Aufg_12_08_Formatierung\n";

   map<string, string> dict;
   dict["anrede"] = "Herr";
   dict["name"] = "Mustermann";
   dict["stadt"] = "Musterstadt";

   string s1("Es wohnte $anrede$ $name$ in $stadt$. Er verlor 23$$ in $stadt$.");
   replace_placeholder(s1, dict);
   cout << s1 << endl;

   string s2("$anrede$ $nachname$");
   replace_placeholder(s2, dict);
   cout << s2 << endl;

   string s3("$anrede$ $name");
   replace_placeholder(s3, dict);
   cout << s3 << endl;
}
