Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<pre><code>#include &lt;iostream&gt; #include &lt;conio.h&gt; #include &lt;string&gt; #include &lt;map&gt; using namespace std; struct Token { enum E { Replace, Literal, Eos }; }; class ParseExp { private: enum State { State_Begin, State_Literal, State_StartRep, State_RepWord, State_EndRep }; string m_str; int m_char; unsigned int m_length; string m_lexme; Token::E m_token; State m_state; public: void Parse(const string&amp; str) { m_char = 0; m_str = str; m_length = str.size(); } Token::E NextToken() { if (m_char &gt;= m_length) m_token = Token::Eos; m_lexme = ""; m_state = State_Begin; bool stop = false; while (m_char &lt;= m_length &amp;&amp; !stop) { char ch = m_str[m_char++]; switch (m_state) { case State_Begin: if (ch == '$') { m_state = State_StartRep; m_token = Token::Replace; continue; } else { m_state = State_Literal; m_token = Token::Literal; } break; case State_StartRep: if (ch == '{') { m_state = State_RepWord; continue; } else continue; break; case State_RepWord: if (ch == '}') { stop = true; continue; } break; case State_Literal: if (ch == '$') { stop = true; m_char--; continue; } } m_lexme += ch; } return m_token; } const string&amp; Lexme() const { return m_lexme; } Token::E Token() const { return m_token; } }; string DoReplace(const string&amp; str, const map&lt;string, string&gt;&amp; dict) { ParseExp exp; exp.Parse(str); string ret = ""; while (exp.NextToken() != Token::Eos) { if (exp.Token() == Token::Literal) ret += exp.Lexme(); else { map&lt;string, string&gt;::const_iterator iter = dict.find(exp.Lexme()); if (iter != dict.end()) ret += (*iter).second; else ret += "undefined(" + exp.Lexme() + ")"; } } return ret; } int main() { map&lt;string, string&gt; words; words["hello"] = "hey"; words["test"] = "bla"; cout &lt;&lt; DoReplace("${hello} world ${test} ${undef}", words); _getch(); } </code></pre> <p>I will be happy to explain anything about this code :)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload