I'm trying to write some very simple functions to escape and unescape strings with respect to XML escape sequences. These are the escape sequences I care about:
unescaped | escaped |
---|---|
' | ' |
" | " |
& | & |
< | < |
> | > |
I've already managed to write the escape_XML()
function, but I'm unsure what the best way to write the inverse function, unescape_XML()
. Is it possible to match on the current string prefix while iterating? I do not have access to any libraries besides the C++ standard library.
Here is a complete example with my code so far:
#include <iostream>
std::string escape_XML(const std::string &input) {
std::string output;
for (char chr : input) {
if (chr == '"') output += """;
else if (chr == '&') output += "&";
else if (chr == '<') output += "<";
else if (chr == '>') output += ">";
else if (chr == '\'') output += "'";
else output += chr;
}
return output;
}
std::string unescape_XML(const std::string &input) {
std::string output;
/* for (char chr : input) {
if (prefix == """) ...
else if (prefix == "&") ...
else if (prefix == "<") ...
else if (prefix == ">") ...
else if (prefix == "'") ...
else output += chr;
} */
return output;
}
int main() {
std::string input{
"\" <-> "\n"
"& <-> &\n"
"< <-> <\n"
"> <-> >\n"
"\' <-> '\n"
};
const std::string escaped = escape_XML(input);
std::cout << "ESCAPED" << std::endl;
std::cout << escaped;
const std::string unescaped = unescape_XML(escaped);
std::cout << "UNESCAPED" << std::endl;
std::cout << unescaped;
std::cout << std::flush;
}