Skip to content

Instantly share code, notes, and snippets.

@baioc
Last active October 16, 2019 22:33
Show Gist options
  • Save baioc/2fbc2f678dd58c88649c9dd8ca0f165a to your computer and use it in GitHub Desktop.
Save baioc/2fbc2f678dd58c88649c9dd8ca0f165a to your computer and use it in GitHub Desktop.
XML tag-balance-checking algorithm
/*
* See the full version at <https://gitlab.com/snippets/1849449>
* and a pure C implementation at <https://gitlab.com/snippets/1837083>
*/
#include <stack>
#include <string>
bool balanced(const std::string& xml)
{
std::stack<std::string> tags;
auto from = 0u;
while (from < xml.length()) {
// check for tag
const auto tag_open = xml.find('<', from);
const auto tag_close = xml.find('>', tag_open);
// no tag found
if (tag_open == std::string::npos)
break;
// incomplete tag
if (tag_close == std::string::npos)
return false;
// get tag
auto tag = xml.substr(tag_open, tag_close + 1 - tag_open);
from = tag_close + 1;
// if its an opening tag, push the closing one
if (tag[1] != '/') {
tags.push(tag.insert(1, "/"));
}
// otherwise (if its a closing tag), check if it was expected
else {
if (tags.empty())
return false;
else if (tags.top() == tag)
tags.pop();
else
return false;
}
}
// all tags must have been closed
return tags.empty();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment